链表排序 Sort List

Posted timhy

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了链表排序 Sort List相关的知识,希望对你有一定的参考价值。

2018-08-11 23:50:30

问题描述:

技术分享图片

问题求解:

解法一、归并排序

    public ListNode sortList(ListNode head) {
        if (head == null || head.next == null)
            return head;
        ListNode prev = null, slow = head, fast = head;
        while (fast != null && fast.next != null) {
            prev = slow;
            slow = slow.next;
            fast = fast.next.next;
        }
        prev.next = null;
        ListNode l1 = sortList(head);
        ListNode l2 = sortList(slow);
        return merge(l1, l2);
    }

    private ListNode merge(ListNode l1, ListNode l2) {
        ListNode dummy = new ListNode(0);
        ListNode p = dummy;
        while (l1 != null && l2 != null) {
            if (l1.val < l2.val) {
                p.next = l1;
                l1 = l1.next;
            }
            else {
                p.next = l2;
                l2 = l2.next;
            }
            p = p.next;
        }
        if (l1 != null) {
            p.next = l1;
        }
        if (l2 != null) {
            p.next = l2;
        }
        return dummy.next;
    }

解法二、快速排序

  public ListNode sortList(ListNode head) {
    if (head == null || head.next == null)
      return head;  
    qsort(head, null);  
    return head;  
  }

    // [begin, end)
    void qsort(ListNode begin, ListNode end) {
        if (begin == end || begin.next == end) return;
        ListNode mid = partition(begin, end);
        qsort(begin, mid);
        qsort(mid.next, end);
    }

    ListNode partition(ListNode begin, ListNode end) {
        int key = begin.val;
        ListNode p = begin;
        ListNode q = begin.next;
        while (q != end) {
            if (q.val < key) {
                p = p.next;
                int tmp = p.val;
                p.val = q.val;
                q.val = tmp;
            }
            q = q.next;
        }
        int tmp = p.val;
        p.val = begin.val;
        begin.val = tmp;
        return p;
    }

 

以上是关于链表排序 Sort List的主要内容,如果未能解决你的问题,请参考以下文章

[Leetcode] Sort list 对链表进行排序

链表排序 Sort List

[LeetCode]148. Sort List链表归并排序

[Leetcode] insertion sort list 链表插入排序

[LintCode] Sort List 链表排序

45.Sort List(链表排序)