-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathleetCode_148.java
More file actions
55 lines (49 loc) · 1.38 KB
/
Copy pathleetCode_148.java
File metadata and controls
55 lines (49 loc) · 1.38 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
/**
* 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 {
public ListNode sortList(ListNode head) {
if(head == null || head.next == null){
return head;
}
ListNode prev = null;
ListNode current = head, future = head;
while(future != null && future.next != null ){
prev = current;
current = current.next;
future = future.next.next;
}
prev.next = null;
ListNode lhs = sortList(head);
ListNode rhs = sortList(current);
return merge(lhs, rhs);
}
ListNode merge(ListNode lhs, ListNode rhs){
ListNode result= new ListNode();
ListNode temp = result;
while(lhs != null && rhs != null){
if(lhs.val < rhs.val){
temp.next = lhs;
lhs = lhs.next;
}else{
temp.next = rhs;
rhs = rhs.next;
}
temp = temp.next;
}
if(lhs != null){
temp.next = lhs;
}
if(rhs!= null){
temp.next = rhs;
}
return result.next;
}
}