forked from doocs/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution.java
45 lines (39 loc) · 1.09 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
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode insertionSortList(ListNode head) {
if (head == null) {
return null;
}
return insertionOneNode(head, head);
}
private ListNode insertionOneNode(ListNode head, ListNode node) {
if (head == null || node == null || node.next == null) {
return head;
}
ListNode perNode = node;
ListNode curNode = node.next;
ListNode nextNode = curNode.next;
if (node.val <= curNode.val) {
return insertionOneNode(head, curNode);
} else {
node.next = nextNode;
}
ListNode pNode = new ListNode(0);
pNode.next = head;
head = pNode;
while (pNode.next.val <= curNode.val) {
pNode = pNode.next;
}
ListNode nNode = pNode.next;
pNode.next = curNode;
curNode.next = nNode;
return insertionOneNode(head.next, perNode);
}
}