File tree Expand file tree Collapse file tree 1 file changed +61
-0
lines changed Expand file tree Collapse file tree 1 file changed +61
-0
lines changed Original file line number Diff line number Diff line change
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
1
62
class Solution {
2
63
public ListNode sortList (ListNode head ) {
3
64
if (head == null || head .next == null ){
You can’t perform that action at this time.
0 commit comments