note: the sort() method can be used to merge to sorted linked list
/**
* 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) {
//lets solve it via merge sort
return sort(head);
}
public ListNode getMiddle(ListNode node){
if(node ==null) return null;
ListNode slow = node;
ListNode fast = node.next;
while(fast!=null && fast.next!=null){ // important
slow = slow.next;
fast = fast.next.next;
}
return slow;
}
public ListNode sort(ListNode node){
if(node==null || node.next ==null) return node;// important base case
ListNode middle = getMiddle(node);
ListNode temp = middle.next;//right
middle.next = null;//left
ListNode left = sort(node);
ListNode right = sort(temp);
return merge(left,right);
}
public ListNode merge(ListNode a, ListNode b){
ListNode head = new ListNode();
ListNode temp = head;
while(a!=null && b!=null){
if(a.val<=b.val){
head.next = new ListNode(a.val);
a = a.next;
}
else{
head.next = new ListNode(b.val);
b = b.next;
}
head = head.next;
}
if(a!=null) head.next = a;
if(b!=null) head.next = b;
return temp.next;
}
}
Top comments (0)