forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
0148-sort-list.java
81 lines (77 loc) · 2.09 KB
/
0148-sort-list.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
/**
* 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){
return head;
}
PriorityQueue<Integer> queue = new PriorityQueue<>();
ListNode temp = head;
while(temp.next!=null){
queue.add(temp.val);
temp = temp.next;
}
queue.add(temp.val);
temp = head;
while(!queue.isEmpty()){
temp.val = queue.poll();
temp = temp.next;
}
return head;
}
}