Skip to content

Commit 7de19ee

Browse files
authored
Merge pull request neetcode-gh#2479 from Anukriti167/patch-4
Update 0148-sort-list.java
2 parents 0c2adfb + 846e6c3 commit 7de19ee

File tree

1 file changed

+61
-0
lines changed

1 file changed

+61
-0
lines changed

java/0148-sort-list.java

Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,64 @@
1+
/**
2+
* Definition for singly-linked list.
3+
* public class ListNode {
4+
* int val;
5+
* ListNode next;
6+
* ListNode() {}
7+
* ListNode(int val) { this.val = val; }
8+
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
9+
* }
10+
*/
11+
class Solution {
12+
// Merge Sort Implementation
13+
public ListNode getMid(ListNode head){
14+
ListNode slow=head, fast=head.next;
15+
while(fast != null && fast.next != null){
16+
fast = fast.next.next;
17+
slow = slow.next;
18+
}
19+
return slow;
20+
}
21+
public ListNode merge(ListNode left, ListNode right){
22+
ListNode dummy = new ListNode();
23+
ListNode tail = dummy;
24+
25+
while(left != null && right != null){
26+
if(left.val < right.val){
27+
tail.next = left;
28+
left = left.next;
29+
}else{
30+
tail.next = right;
31+
right = right.next;
32+
}
33+
tail = tail.next;
34+
}
35+
if(left != null){
36+
tail.next = left;
37+
}
38+
if(right != null){
39+
tail.next = right;
40+
}
41+
return dummy.next;
42+
}
43+
public ListNode sortList(ListNode head) {
44+
if(head == null || head.next == null){
45+
return head;
46+
}
47+
48+
// Split the list in 2 halfs
49+
ListNode left = head;
50+
ListNode right = getMid(head);
51+
ListNode tmp = right.next;
52+
right.next = null;
53+
right = tmp;
54+
55+
left = sortList(left);
56+
right = sortList(right);
57+
return merge(left, right);
58+
}
59+
}
60+
61+
// Using a Heap to sort the list
162
class Solution {
263
public ListNode sortList(ListNode head) {
364
if(head == null || head.next == null){

0 commit comments

Comments
 (0)