Skip to content

Commit

Permalink
Merge pull request neetcode-gh#2479 from Anukriti167/patch-4
Browse files Browse the repository at this point in the history
Update 0148-sort-list.java
  • Loading branch information
a93a authored May 17, 2023
2 parents 0c2adfb + 846e6c3 commit 7de19ee
Showing 1 changed file with 61 additions and 0 deletions.
61 changes: 61 additions & 0 deletions java/0148-sort-list.java
Original file line number Diff line number Diff line change
@@ -1,3 +1,64 @@
/**
* 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 {
// Merge Sort Implementation
public ListNode getMid(ListNode head){
ListNode slow=head, fast=head.next;
while(fast != null && fast.next != null){
fast = fast.next.next;
slow = slow.next;
}
return slow;
}
public ListNode merge(ListNode left, ListNode right){
ListNode dummy = new ListNode();
ListNode tail = dummy;

while(left != null && right != null){
if(left.val < right.val){
tail.next = left;
left = left.next;
}else{
tail.next = right;
right = right.next;
}
tail = tail.next;
}
if(left != null){
tail.next = left;
}
if(right != null){
tail.next = right;
}
return dummy.next;
}
public ListNode sortList(ListNode head) {
if(head == null || head.next == null){
return head;
}

// Split the list in 2 halfs
ListNode left = head;
ListNode right = getMid(head);
ListNode tmp = right.next;
right.next = null;
right = tmp;

left = sortList(left);
right = sortList(right);
return merge(left, right);
}
}

// Using a Heap to sort the list
class Solution {
public ListNode sortList(ListNode head) {
if(head == null || head.next == null){
Expand Down

0 comments on commit 7de19ee

Please sign in to comment.