forked from ghostmkg/Learning-Stories-Repository
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcs.java
More file actions
63 lines (61 loc) · 1.49 KB
/
cs.java
File metadata and controls
63 lines (61 loc) · 1.49 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
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode sortList(ListNode head) {
if(head==null || head.next==null){
return head;
}
ListNode mid=getmid(head);
ListNode nxtmid=mid.next;
mid.next=null;
ListNode left=sortList(head);
ListNode right=sortList(nxtmid);
return merge(left,right);
}
public static ListNode merge(ListNode l,ListNode r){
if(l==null)return r;
if(r==null)return l;
ListNode head=null,tail=null;
if(l.val<=r.val){
head=tail=l;
l=l.next;
}else{
head=tail=r;
r=r.next;
}
while(l!=null && r!=null){
if(l.val<=r.val){
tail.next=l;
tail=l;
l=l.next;
}else{
tail.next=r;
tail=r;
r=r.next;
}
}
if(l!=null){
tail.next=l;
}else{
tail.next=r;
}
return head;
}
public static ListNode getmid(ListNode head){
ListNode slow=head;
ListNode fast=head.next;
while(fast!=null && fast.next!=null){
fast=fast.next.next;
slow=slow.next;
}
return slow;
}
}