148. Sort List
Sort a linked list in O(n log n) time using constant space complexity.
Hide Similar Problems
Merge sort for Linked List.
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ public class Solution { public ListNode sortList(ListNode head) { if(head == null || head.next == null) return head; ListNode f = head.next.next; ListNode p = head; while (f != null && f.next != null) { p = p.next; f = f.next.next; } ListNode sortedSecondHalf = sortList(p.next); p.next = null; ListNode sortedFirstHalf = sortList(head); return merge(sortedFirstHalf, sortedSecondHalf); } public ListNode merge(ListNode l1, ListNode l2) { if(l1 == null) return l2; if(l2 == null) return l1; ListNode sorted = new ListNode(0); ListNode ret = sorted; while(l1 != null && l2 != null) { if(l1.val < l2.val) { ret.next = l1; l1 = l1.next; } else { ret.next = l2; l2 = l2.next; } ret = ret.next; } if(l1 != null) ret.next = l1; if(l2 != null) ret.next = l2; return sorted.next; } }

浙公网安备 33010602011771号