66 * Created by liwentian on 2017/9/11.
77 */
88
9+ /**
10+ * 这题采用merge sort,可自顶向下或自底向上
11+ * 区别是自顶向下是递归的,需要额外的空间
12+ * 而自底向上不用
13+ * 时间复杂度都是O(nlgn)
14+ */
915public class SortList {
1016
17+ /**
18+ * 自顶向下
19+ */
1120 public ListNode sortList (ListNode head ) {
1221 if (head == null || head .next == null )
1322 return head ;
@@ -27,26 +36,70 @@ public ListNode sortList(ListNode head) {
2736 }
2837
2938 ListNode merge (ListNode l1 , ListNode l2 ) {
30- ListNode l = new ListNode (0 ), p = l ;
31-
32- while (l1 != null && l2 != null ) {
39+ ListNode dummy = new ListNode (0 ), cur = dummy ;
40+ for ( ; l1 != null && l2 != null ; ) {
3341 if (l1 .val < l2 .val ) {
34- p .next = l1 ;
42+ cur .next = l1 ;
3543 l1 = l1 .next ;
36- } else {
37- p .next = l2 ;
44+ } else {
45+ cur .next = l2 ;
3846 l2 = l2 .next ;
3947 }
40- p = p .next ;
48+ cur = cur .next ;
4149 }
50+ cur .next = l1 != null ? l1 : l2 ;
51+ return dummy .next ;
52+ }
4253
43- if (l1 != null )
44- p .next = l1 ;
45-
46- if (l2 != null )
47- p .next = l2 ;
54+ /**
55+ * 自底向上
56+ */
57+ public ListNode sortList2 (ListNode head ) {
58+ int size = 0 ;
59+ for (ListNode node = head ; node != null ; node = node .next , size ++);
60+ ListNode dummy = new ListNode (0 );
61+ ListNode left , right , cur , tail ;
62+ for (int step = 1 ; step <= size ; step *= 2 ) {
63+ for (cur = head , tail = dummy ; cur != null ; ) {
64+ left = cur ;
65+ right = split (left , step );
66+ cur = split (right , step );
67+ tail = merge (left , right , tail );
68+ }
69+ head = dummy .next ;
70+ }
71+ return dummy .next ;
72+ }
4873
49- return l .next ;
74+ /**
75+ * 将l1和l2合并后挂在tail下,返回新的tail
76+ */
77+ ListNode merge (ListNode l1 , ListNode l2 , ListNode tail ) {
78+ for ( ; l1 != null && l2 != null ; ) {
79+ if (l1 .val < l2 .val ) {
80+ tail .next = l1 ;
81+ l1 = l1 .next ;
82+ } else {
83+ tail .next = l2 ;
84+ l2 = l2 .next ;
85+ }
86+ tail = tail .next ;
87+ }
88+ tail .next = l1 != null ? l1 : l2 ;
89+ for ( ; tail .next != null ; tail = tail .next );
90+ return tail ;
5091 }
5192
93+ /**
94+ * 从start开始取step个节点,返回下一个节点
95+ */
96+ private ListNode split (ListNode start , int step ) {
97+ for (step --; start != null && step > 0 ; step --, start = start .next );
98+ if (start != null && start .next != null ) {
99+ ListNode next = start .next ;
100+ start .next = null ;
101+ return next ;
102+ }
103+ return null ;
104+ }
52105}
0 commit comments