forked from xiaoyaoworm/Leetcode-java
-
Notifications
You must be signed in to change notification settings - Fork 0
/
148_sortList.java
67 lines (61 loc) · 1.59 KB
/
148_sortList.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
//http://xiaoyaoworm.com/blog/2015/04/03/%E6%96%B0leetcode-sort-1-sort-list/
/**
* Definition for singly-linked list.
* class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode sortList(ListNode head) {
if(head == null || head.next == null) return head;
int length = 0;
ListNode p = head;
while(p!=null){
length++;
p = p.next;
}
int mid = length/2;
int n = 1; //pay attention, this is not 0!!!!
ListNode l = head;
ListNode r = null;
p = head;
while(n <= mid){
if(n == mid){
r = p.next;
p.next = null;
break;
}
n++;
p = p.next;
}
ListNode sortedL = sortList(l);
ListNode sortedR = sortList(r);
return merge(sortedL, sortedR);
}
public ListNode merge(ListNode p1, ListNode p2){
ListNode fake = new ListNode(0);
ListNode result = fake;
while(p1!=null && p2!=null){
if(p1.val <= p2.val){
fake.next = new ListNode(p1.val);
p1 = p1.next;
} else {
fake.next = new ListNode(p2.val);
p2 = p2.next;
}
fake = fake.next;
}
if(p1!=null){
fake.next = p1;
}
if(p2!=null){
fake.next = p2;
}
return result.next;
}
}