LintCode : 链表排序

来源:互联网 发布:java 预测算法 编辑:程序博客网 时间:2024/05/21 09:06

链表排序

  •  描述
  •  笔记
  •  数据
  •  评测

在 O(n log n) 时间复杂度和常数级的空间复杂度下给链表排序。

您在真实的面试中是否遇到过这个题? 
Yes
样例

给出 1->3->2->null,给它排序变成 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 mid = findMiddenNode(head);        ListNode right = mid.next;        mid.next = null;        ListNode sortLeft = sortList(head);        ListNode sortRight = sortList(right);        return mergeSort(sortLeft, sortRight);    }        public static ListNode findMiddenNode(ListNode head) {        ListNode slow = head;        ListNode fast = head.next;        while (fast != null && fast.next != null) {            slow = slow.next;            fast = fast.next.next;        }        return slow;    }        public ListNode mergeSort(ListNode left, ListNode right) {        ListNode head = new ListNode(-1);        ListNode res = head;        while (left != null && right != null) {            if (left.val > right.val) {                res.next = right;                right = right.next;                res = res.next;            } else {                res.next = left;                left = left.next;                res = res.next;            }        }        if (left != null) {            res.next = left;        }        if (right != null) {            res.next = right;        }        return head.next;    }}

0 0
原创粉丝点击