-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathInsertionSortList.java
More file actions
62 lines (61 loc) · 1.76 KB
/
InsertionSortList.java
File metadata and controls
62 lines (61 loc) · 1.76 KB
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
53
54
55
56
57
58
59
60
61
62
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode insertionSortList(ListNode head) {
ListNode sentinel = new ListNode(0);
ListNode pre = sentinel;
ListNode cur = head;
while (cur != null) {
ListNode next = cur.next;
while (pre.next != null && pre.next.val < cur.val) {
pre = pre.next;
}
cur.next = pre.next;
pre.next = cur;
pre = sentinel;
cur = next;
}
return sentinel.next;
}
}
public class Solution {
public ListNode insertionSortList(ListNode head) {
ListNode sortHead = null, sortTail = null;
ListNode cur = head;
while (cur != null) {
ListNode insert = cur;
cur = cur.next;
insert.next = null;
if (sortHead == null) {
sortHead = insert;
sortTail = insert;
}
else if (insert.val <= sortHead.val) {
insert.next = sortHead;
sortHead = insert;
}
else if (insert.val > sortTail.val) {
sortTail.next = insert;
sortTail = insert;
}
else {
ListNode sortCur = sortHead;
while(sortCur.next != null) {
if (sortCur.next.val >= insert.val) {
insert.next = sortCur.next;
sortCur.next = insert;
break;
}
sortCur = sortCur.next;
}
}
}
return sortHead;
}
}