MergeSort
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
| class Solution { public ListNode sortList(ListNode head) { if (head == null || head.next == null) { return head; }
ListNode fast = head, slow = new ListNode(-1, head);
while (fast != null && fast.next != null) { fast = fast.next.next; slow = slow.next; }
ListNode rightHead = slow.next; slow.next = null;
ListNode orderedHeadA = sortList(head); ListNode orderedHeadB = sortList(rightHead);
ListNode dummyHead = new ListNode(); ListNode pre = dummyHead, nodeA = orderedHeadA, nodeB = orderedHeadB; while (nodeA != null && nodeB != null) { if (nodeA.val <= nodeB.val) { pre.next = nodeA; nodeA = nodeA.next; } else { pre.next = nodeB; nodeB = nodeB.next; } pre = pre.next; } pre.next = nodeA != null ? nodeA : nodeB;
return dummyHead.next; } }
|
MergeSort
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 79
| class Solution { public ListNode sortList(ListNode head) { if (head == null || head.next == null) { return head; }
ListNode dummyHead = new ListNode(); dummyHead.next = head;
int length = getLength(head);
for (int pieceLength = 1; pieceLength < length; pieceLength *= 2) { ListNode pre = dummyHead; ListNode curr = pre.next;
while (curr != null) { int i = pieceLength; ListNode l1 = curr; while (curr != null && i > 0) { curr = curr.next; i--; }
if (i > 0) { break; }
ListNode l2 = curr; i = pieceLength; while (curr != null && i > 0) { curr = curr.next; i--; }
ListNode nextPairStartNode = curr;
int l1Length = pieceLength, l2Length = pieceLength - i; while (l1Length > 0 && l2Length > 0) { if (l1.val < l2.val) { pre.next = l1; l1 = l1.next; l1Length--; } else { pre.next = l2; l2 = l2.next; l2Length--; } pre = pre.next; }
pre.next = l1Length > 0 ? l1 : l2; while (l1Length > 0 || l2Length > 0) { pre = pre.next; l1Length--; l2Length--; }
pre.next = nextPairStartNode; } }
return dummyHead.next; }
private int getLength(ListNode node) { int length = 0; while (node != null) { length++; node = node.next; } return length; } }
|
迭代法细节较多,想一次写对还是比较困难。
References
148. Sort List
剑指 Offer II 077. 链表排序