Skip to content

Merge Sort in Linked List #1441

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
kunal2504java opened this issue Jan 28, 2025 · 0 comments
Open

Merge Sort in Linked List #1441

kunal2504java opened this issue Jan 28, 2025 · 0 comments

Comments

@kunal2504java
Copy link

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;
}

}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant