标签:else pre lis ace val public 含义 logs sort
Sort a linked list in O(n log n) time using constant space complexity.
含义:为一个列表排序,要求空间复杂度为常量
思路:使用归并排序
1 class Solution { 2 private ListNode mergeNode(ListNode l1, ListNode l2) { 3 ListNode head = new ListNode(0); 4 ListNode p = head; 5 while (l1 != null && l2 != null) { 6 if (l1.val < l2.val) { 7 p.next = l1; 8 l1 = l1.next; 9 } else { 10 p.next = l2; 11 l2 = l2.next; 12 } 13 p = p.next; 14 } 15 if (l1 != null) p.next = l1; 16 if (l2 != null) p.next = l2; 17 return head.next; 18 } 19 20 public ListNode sortList(ListNode head) { 21 if (head == null || head.next == null) return head; 22 ListNode walker = head, runner = head; 23 while (runner != null && runner.next != null) { 24 walker = walker.next; 25 runner = runner.next.next; 26 } 27 ListNode l1 = sortList(head); 28 ListNode l2 = sortList(walker); 29 return mergeNode(l1, l2); 30 } 31 }
标签:else pre lis ace val public 含义 logs sort
原文地址:http://www.cnblogs.com/wzj4858/p/7729381.html