-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathInsertionSortList.java
More file actions
33 lines (33 loc) · 1.13 KB
/
Copy pathInsertionSortList.java
File metadata and controls
33 lines (33 loc) · 1.13 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
/**
* Sort a linked list using insertion sort.
*
* @author joshluo
*
* Answer: Iterating through two list. Try saving time when figuring out which one should be re-ordered.
*/
public class InsertionSortList {
public ListNode insertionSortList(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode preHead = new ListNode(Integer.MIN_VALUE);
preHead.next = head;
while (head != null && head.next != null) {
if (head.val > head.next.val) { // Figure out which is not in order. Save time!!
ListNode current = preHead;
ListNode insertNode = head.next;
// find position for insertNode
while (current.next.val <= insertNode.val) {
current = current.next;
}
ListNode temp = current.next;
current.next = insertNode;
head.next = insertNode.next;
insertNode.next = temp;
} else {
head = head.next;
}
}
return preHead.next;
}
}