-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathInsertionSortList.java
More file actions
52 lines (46 loc) · 949 Bytes
/
InsertionSortList.java
File metadata and controls
52 lines (46 loc) · 949 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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
/**
*
*/
package cc.dectinc.leetcode;
import cc.dectinc.api.structs.ListNode;
/**
* @author Dectinc
* @version Apr 16, 2015 9:26:01 PM
*
*/
public class InsertionSortList {
public ListNode insertionSortList(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode dummy = new ListNode(0);
dummy.next = head;
ListNode q = head.next, t = head;
ListNode p, r;
while (q != null) {
r = dummy;
p = dummy.next;
int val = q.val;
while (p != q && val > p.val) {
r = p;
p = p.next;
}
if (p == q) {
q = q.next;
t = t.next;
} else {
t.next = q.next;
q.next = p;
r.next = q;
q = t.next;
}
}
return dummy.next;
}
public static void main(String[] args) {
InsertionSortList sol = new InsertionSortList();
ListNode head = ListNode
.constructList(new Integer[] { 5, 1, 4, 0, 3, 2 });
System.out.println(sol.insertionSortList(head));
}
}