【LeetCode】#148排序連結串列(Sort List)
阿新 • • 發佈:2018-12-20
【LeetCode】#148排序連結串列(Sort List)
題目描述
在 O(n log n) 時間複雜度和常數級空間複雜度下,對連結串列進行排序。
示例
示例 1:
輸入: 4->2->1->3
輸出: 1->2->3->4
示例 2:
輸入: -1->5->3->4->0
輸出: -1->0->3->4->5
Description
Sort a linked list in O(n log n) time using constant space complexity.
Example
Example 1:
Input: 4->2->1->3
Output: 1->2->3->4
Example 2:
Input: -1->5->3->4->0
Output: -1->0->3->4->5
解法
class Solution { public ListNode sortList(ListNode head) { return head == null ? null : mergeSort(head); } private ListNode mergeSort(ListNode head){ if(head.next==null){ return head; } ListNode p = head, q = head, pre = null; while(q!=null && q.next!=null){ pre = p; p = p.next; q = q.next.next; } pre.next = null; ListNode l = mergeSort(head); ListNode r = mergeSort(p); return merge(l, r); } ListNode merge(ListNode l, ListNode r){ ListNode dummyHead = new ListNode(0); ListNode cur = dummyHead; while(l!=null && r!=null){ if(l.val<=r.val){ cur.next = l; cur = cur.next; l = l.next; }else{ cur.next = r; cur = cur.next; r = r.next; } } if(l!=null){ cur.next = l; } if(r!=null){ cur.next = r; } return dummyHead.next; } }