forked from walnutown/CodingInTheDeep
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathInsertionSortList.java
More file actions
37 lines (35 loc) · 959 Bytes
/
Copy pathInsertionSortList.java
File metadata and controls
37 lines (35 loc) · 959 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
/*
Sort a linked list using insertion sort.
*/
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
// Note to disconnect the node from the list when move its position
// time: O(n^2); space: O(1)
public class Solution {
public ListNode insertionSortList(ListNode head) {
if (head==null || head.next==null)
return head;
ListNode sen = new ListNode(Integer.MIN_VALUE); sen.next = head;
ListNode p = head.next;
head.next = null; // cut the list here to avoid endless loop
while (p!=null){
ListNode next = p.next;
ListNode s = sen;
while (s.next!=null && s.next.val < p.val)
s = s.next;
p.next = s.next;
s.next = p;
p = next;
}
return sen.next;
}
}