148. Sort List

来源:互联网 发布:.sql文件导入数据库 编辑:程序博客网 时间:2024/05/22 07:14

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

归并

/** * 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;        // get mid        ListNode mid = getmid(head);        //sort        ListNode tmp = mid.next;        mid.next = null;        ListNode midleft = sortList(head);        ListNode midright = sortList(tmp);        //merge        return merge(midleft, midright);    }    public ListNode getmid(ListNode head) {        ListNode fast = head.next;        ListNode slow = head;        while (fast != null && fast.next != null) {            fast = fast.next.next;            slow = slow.next;        }        return slow;    }    public ListNode merge(ListNode midleft, ListNode midright) {        ListNode dummy = new ListNode(0);        ListNode node = dummy;        while (midleft != null && midright != null) {            if (midleft.val < midright.val) {                node.next = midleft;                node = node.next;                midleft = midleft.next;            } else {                node.next = midright;                node = node.next;                midright = midright.next;            }        }        if(midleft != null) node.next = midleft;        if(midright != null) node.next = midright;        return dummy.next;    }}

快排

/** * 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;        //pivot        ListNode pivot = head;        head = head.next;        pivot.next = null;        ListNode p = pivot;        //small, large        ListNode small = new ListNode(0);        ListNode large = new ListNode(0);        ListNode s = small;        ListNode l = large;        while (head != null) {            if (head.val < pivot.val) {                s.next = head;                head = head.next;                s = s.next;            } else if (head.val == pivot.val) {                p.next = head;                head = head.next;                p = p.next;            } else {                l.next = head;                head = head.next;                l = l.next;            }        }        //merge        s.next = null;        l.next = null;        ListNode res = sortList(small.next);        if (res == null) res = pivot;        else {            ListNode tmp = res;            while (tmp.next != null) tmp = tmp.next;            tmp.next = pivot;        }        p.next = sortList(large.next);        return res;    }}
0 0
原创粉丝点击