Sort a linked list in O(n log n) time using constant space complexity.
Example
Given 1-3->2->null, sort it to 1->2->3->null.
/** * Definition for ListNode. * public class ListNode { * int val; * ListNode next; * ListNode(int val) { * this.val = val; * this.next = null; * } * } */ public class Solution { /** * @param head: The head of linked list. * @return: You should return the head of the sorted linked list, using constant space complexity. */ public ListNode sortList(ListNode head) { // write your code here if(head == null || head.next == null) return head; ListNode slow = head; ListNode fast = head; while(fast != null && fast.next != null && fast.next.next != null){ slow = slow.next; fast = fast.next.next; } ListNode head2 = slow.next; slow.next = null; head = sortList(head); head2 = sortList(head2); head = merge(head, head2); return head; } public ListNode merge(ListNode head1, ListNode head2){ if(head1 == null) return head2; if(head2 == null) return head1; ListNode fakehead = new ListNode(0); ListNode p = fakehead; ListNode p1 = head1; ListNode p2 = head2; while(p1 != null || p2 != null){ int num1 = Integer.MAX_VALUE; int num2 = Integer.MAX_VALUE; if(p1 != null) num1 = p1.val; if(p2 != null) num2 = p2.val; if(num1 < num2){ p.next = p1; p = p.next; p1 = p1.next; } else{ p.next = p2; p = p.next; p2 = p2.next; } } return fakehead.next; } }
时间: 2024-10-11 13:54:59