-
Notifications
You must be signed in to change notification settings - Fork 79
/
Solution.java
70 lines (53 loc) · 1.55 KB
/
Solution.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
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
63
64
65
66
67
68
69
70
package five;
/**
* @author dmrfcoder
* @date 2019/4/10
*/
class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
next = null;
}
}
public class Solution {
public ListNode insertionSortList(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode tempHead = new ListNode(0);
tempHead.next = head;
ListNode curNode = head;
ListNode indexNode;
while (curNode != null) {
indexNode = curNode.next;
while (indexNode != null && indexNode.val >= curNode.val) {
indexNode = indexNode.next;
curNode = curNode.next;
}
if (indexNode == null) {
return tempHead.next;
}
ListNode copyOfTempHead = tempHead;
ListNode copyOfHead = tempHead.next;
while (copyOfHead.val < indexNode.val) {
copyOfTempHead = copyOfTempHead.next;
copyOfHead = copyOfHead.next;
}
copyOfTempHead.next = indexNode;
curNode.next = indexNode.next;
indexNode.next = copyOfHead;
}
return tempHead.next;
}
public static void main(String[] args) {
ListNode head = new ListNode(3);
ListNode node2 = new ListNode(2);
ListNode node1 = new ListNode(1);
head.next = node2;
node2.next = node1;
Solution solution = new Solution();
solution.insertionSortList(head);
}
}