-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathInsertionSortList.java
More file actions
42 lines (42 loc) · 1.42 KB
/
Copy pathInsertionSortList.java
File metadata and controls
42 lines (42 loc) · 1.42 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
public class InsertionSortList{
public static ListNode insertionSortList(ListNode head) {
if(head == null || head.next == null)
return head;
ListNode resHead = null;
ListNode resTail = null;
while( head != null){
ListNode curr = head;
head = head.next;
// insert before the head
if( resHead == null){
resHead = curr;
resTail = curr;
resTail.next = null;
} else if(curr.val <= resHead.val){
curr.next = resHead;
resHead = curr;
} else if(curr.val >= resTail.val){
resTail.next = curr;
resTail = curr;
resTail.next = null;
} else {
ListNode findPos = resHead;
while(findPos != null){
if(findPos.next == null || curr.val < findPos.next.val){
curr.next = findPos.next;
findPos.next = curr;
break;
}
findPos = findPos.next;
}
}
}
return resHead;
}
public static void main(String args[]){
ListNode test = ListNode.testCase();
System.out.println(test);
System.out.println("----------------");
System.out.println(insertionSortList(test));
}
}