Skip to content

Merge Sort in Linked List #1441

Description

@kunal2504java

There are a few minor issues in the code ig , Because the code throws some error while submitting on leetcode
I have written a code that works fine and follows the same approach as shown in the video
class Solution {
public ListNode sortList(ListNode head) {
if (head == null || head.next == null) {
return head;
}
// Find the middle of the list
ListNode mid = getMid(head);
ListNode left = sortList(head);
ListNode right = sortList(mid);
return merge(left, right);
}

ListNode merge(ListNode list1, ListNode list2) {
    ListNode dummyHead = new ListNode(); 
    ListNode tail = dummyHead; 

    while (list1 != null && list2 != null) {
        if (list1.val < list2.val) {
            tail.next = list1; 
            list1 = list1.next; 
        } else {
            tail.next = list2; 
            list2 = list2.next; 
        }
        tail = tail.next; 
    }

    tail.next = (list1 != null) ? list1 : list2;

    return dummyHead.next; 
}

ListNode getMid(ListNode head) {
    ListNode midPrev = null; 
    while (head != null && head.next != null) {
        midPrev = (midPrev == null) ? head : midPrev.next; // Move midPrev forward
        head = head.next.next; 
    }
    ListNode mid = midPrev.next;
    midPrev.next = null; 
    return mid;
}

}

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions