forked from alexkoby/Leetcode-Problems
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path148. Sort List
More file actions
77 lines (70 loc) · 2.11 KB
/
148. Sort List
File metadata and controls
77 lines (70 loc) · 2.11 KB
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
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode sortList(ListNode head) {
if(head == null){
return null;
}
//1 Element is by default sorted
if(head.next == null){
return head;
}
ListNode leftHalf = head;
ListNode rightHalf = findMiddleNodeAndSplitList(head);
leftHalf = sortList(leftHalf);
rightHalf = sortList(rightHalf);
return merge(leftHalf, rightHalf);
}
public ListNode findMiddleNodeAndSplitList(ListNode head){
ListNode leader = head;
ListNode follower = head;
while(leader.next != null && leader.next.next != null){
leader = leader.next.next;
follower = follower.next;
}
//Last while loop never got hit -- length 1 or 2
ListNode retval = follower.next;
follower.next = null;
return retval;
}
public ListNode merge(ListNode left, ListNode right){
ListNode realList;
ListNode retval;
if(left.val < right.val){
retval = left;
realList = left;
left = left.next;
}
else{
retval = right;
realList = right;
right = right.next;
}
while(left != null && right != null){
if(left.val < right.val){
realList = realList.next = left;
left = left.next;
}
else{
realList = realList.next = right;
right = right.next;
}
}
//only this or the next while loop will execute because they both can't be true or you'd still be in above while loop
while(left != null){
realList = realList.next = left;
left = left.next;
}
while(right != null){
realList = realList.next = right;
right = right.next;
}
return retval;
}
}