forked from lilong-dream/LeetCode-Java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path148SortList.java
More file actions
78 lines (64 loc) · 1.75 KB
/
148SortList.java
File metadata and controls
78 lines (64 loc) · 1.75 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
78
// Author: Li Long, [email protected]
// Date: Apr 17, 2014
// Source: http://oj.leetcode.com/problems/sort-list/
// Analysis: http://blog.csdn.net/lilong_dream/article/details/20284389
//Sort a linked list in O(n log n) time using constant space complexity.
/**
* Definition for singly-linked list.
* class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class SortList {
public ListNode sortList(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode fast = head;
ListNode slow = head;
while (fast.next != null) {
fast = fast.next.next;
if (fast == null) {
break;
}
slow = slow.next;
}
ListNode right = slow.next;
slow.next = null;
ListNode left = sortList(head);
right = sortList(right);
return merge(left, right);
}
// Reuse Merge Two Sorted Lists
public ListNode merge(ListNode left, ListNode right) {
MergeTwoSortedLists helper = new MergeTwoSortedLists();
return helper.mergeTwoLists(left, right);
}
public void printList(ListNode node) {
while (node != null) {
System.out.print(node.val + "->");
node = node.next;
}
System.out.println(" ");
}
public static void main(String[] args) {
SortList slt = new SortList();
ListNode n1 = new ListNode(8);
ListNode n2 = new ListNode(5);
ListNode n3 = new ListNode(3);
ListNode n4 = new ListNode(4);
n1.next = n2;
n2.next = n3;
n3.next = n4;
System.out.println("Before sort:");
slt.printList(n1);
ListNode res = slt.sortList(n1);
System.out.println("After sort:");
slt.printList(res);
}
}