DEV Community

Prashant Mishra
Prashant Mishra

Posted on

Sort the given LinkedList

problem

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) {
        // using merge sort on the given list
        return merge(head);
    }

    public ListNode merge(ListNode head) {
        if (head == null || head.next == null)
            return head;
        ListNode middleNode = findMiddleNode(head);
        ListNode next = middleNode.next;
        middleNode.next = null;

        ListNode left = merge(head);
        ListNode right = merge(next);
        ListNode sortedNode = sort(left, right);
        return sortedNode;
    }

    public ListNode sort(ListNode l, ListNode r) {
        // base case
        if (l == null)
            return r;
        else if (r == null)
            return l;
        ListNode result = null;

        if (l.val < r.val) {
            result = l;
            result.next = sort(l.next, r);
        } else {
            result = r;
            result.next = sort(l, r.next);

        }
        return result;
    }

    public ListNode findMiddleNode(ListNode head) {
        if (head == null)
            return head;
        ListNode slow = head;
        ListNode faster = head;
        // 1>2>3>null
        // 1>2>null
        // null
        while (faster.next != null && faster.next.next != null) {
            slow = slow.next;
            faster = faster.next.next;
        }
        return slow;
    }
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)

Great read:

Is it Time to go Back to the Monolith?

History repeats itself. Everything old is new again and I’ve been around long enough to see ideas discarded, rediscovered and return triumphantly to overtake the fad. In recent years SQL has made a tremendous comeback from the dead. We love relational databases all over again. I think the Monolith will have its space odyssey moment again. Microservices and serverless are trends pushed by the cloud vendors, designed to sell us more cloud computing resources.

Microservices make very little sense financially for most use cases. Yes, they can ramp down. But when they scale up, they pay the costs in dividends. The increased observability costs alone line the pockets of the “big cloud” vendors.