- Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathsortList.java
More file actions
Latest commit
38 lines (36 loc) · 1004 Bytes
/
Copy pathsortList.java
File metadata and controls
38 lines (36 loc) · 1004 Bytes
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
publicclassSolution {
//Merge sort for a List
//time complexity: O(nlog(n))
ListNodegetMiddleOfList(ListNodehead) {
ListNodeslow = head;
ListNodefast = head;
while(fast.next!=null&&fast.next.next!=null) {
slow = slow.next;
fast = fast.next.next;
}
returnslow;
}
publicListNodesortList(ListNodehead) {
if(head==null||head.next==null) {
returnhead;
}
ListNodemiddle = getMiddleOfList(head);
ListNodenext = middle.next;
middle.next = null;
returnmergeList(sortList(head), sortList(next));
}
ListNodemergeList(ListNodea, ListNodeb) {
ListNodedummyHead = newListNode(-1);
ListNodecurr = dummyHead;
while(a!=null&&b!=null) {
if(a.val<=b.val) {
curr.next=a;a=a.next;
} else {
curr.next=b;b=b.next;
}
curr = curr.next;
}
curr.next = a!=null?a:b;
returndummyHead.next;
}
}