-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSortList.java
More file actions
74 lines (54 loc) · 1.46 KB
/
SortList.java
File metadata and controls
74 lines (54 loc) · 1.46 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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
public class SortList {
class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
next = null;
}
}
public ListNode sortList(ListNode head) {
if(head==null||head.next==null)
return head;
return mergeSort(head);
}
ListNode mergeSort(ListNode head){
if(head==null||head.next==null)
return head;
ListNode p = head, fast = head;
ListNode prep = null;
while(fast!=null && fast.next!=null){
prep = p;
p=p.next;
fast=fast.next.next;
}
prep.next = null;
ListNode left = mergeSort(head);
ListNode right = mergeSort(p);
return merge(left,right);
}
ListNode merge(ListNode l, ListNode r){
ListNode tmpHead = new ListNode(0);
ListNode p = tmpHead;
while(l!=null && r!=null){
if(l.val<=r.val){
p.next=l;
l=l.next;
}
else{
p.next=r;
r=r.next;
}
p=p.next;
}
if(l==null){
p.next=r;
}
else{
p.next=l;
}
// p=tmpHead.next;
//tmpHead.next=null;
return tmpHead.next;
}
}