Sort List

来源:互联网 发布:想在淘宝开店没有货源 编辑:程序博客网 时间:2024/05/12 02:09

Q:

Sort a linked list in O(n log n) time using constant space complexity.

Solution:

Linked list merge sort.

/** * Definition for singly-linked list. * class ListNode { *     int val; *     ListNode next; *     ListNode(int x) { *         val = x; *         next = null; *     } * } */public class Solution {    public ListNode sortList(ListNode head) {        if (head == null || head.next == null)            return head;        ListNode slow = head;        ListNode fast = head.next.next;        while (fast != null && fast.next != null) {            slow = slow.next;            fast = fast.next.next;        }        ListNode mid = slow.next;        slow.next = null;        ListNode l1 = sortList(head);        ListNode l2 = sortList(mid);        return merge(l1, l2);    }        ListNode merge(ListNode l1, ListNode l2) {        ListNode head = new ListNode(0);        ListNode p = head;        while (l1 != null && l2 != null) {            if (l1.val < l2.val) {                p.next = l1;                p = p.next;                l1 = l1.next;            }            else {                p.next = l2;                p = p.next;                l2 = l2.next;            }        }        if (l1 == null)            p.next = l2;        if (l2 == null)            p.next = l1;        return head.next;    }}


0 0
原创粉丝点击