-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathInsertion Sort List.java
More file actions
60 lines (55 loc) · 1.61 KB
/
Insertion Sort List.java
File metadata and controls
60 lines (55 loc) · 1.61 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
/*
Sort a linked list using insertion sort.
*/
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode insertionSortList(ListNode head) {
// IMPORTANT: Please reset any member data you declared, as
// the same Solution instance will be reused for each test case.
if (head == null) return null;
ListNode newHead = null;
ListNode newTail = null;
int min = head.val;
while (head != null) {
ListNode next = head.next;
ListNode node = head;
ListNode curMin = null;
while (node != null) {
if (curMin == null) curMin = node;
if (node.val < curMin.val) curMin = node;
node = node.next;
}
if (newHead == null) {
newHead = curMin;
newTail = curMin;
} else {
newTail.next = curMin;
newTail = curMin;
}
//remove curMin from original list
node = head;
if (curMin == head) {
head = next;
} else {
while (node.next != null) {
if (node.next == curMin) {
node.next = node.next.next;
break;
}
node = node.next;
}
}
}
return newHead;
}
}