-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathInsertionSortLL.java
30 lines (26 loc) · 933 Bytes
/
InsertionSortLL.java
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
import java.util.*;
class InsertionSortLL{
public ListNode insertionSortList(ListNode ptr) {
if (ptr == null || ptr.next == null)
return ptr;
ListNode preInsert, toInsert, dummyHead = new ListNode(0);
dummyHead.next = ptr;
while (ptr != null && ptr.next != null) {
if (ptr.val <= ptr.next.val) {
ptr = ptr.next;
} else {
toInsert = ptr.next;
// Locate preInsert.
preInsert = dummyHead;
while (preInsert.next.val < toInsert.val) {
preInsert = preInsert.next;
}
ptr.next = toInsert.next;
// Insert toInsert after preInsert.
toInsert.next = preInsert.next;
preInsert.next = toInsert;
}
}
return dummyHead.next;
}
}