关闭

sort-list(Leetcode)

标签: leetcode归并排序
96人阅读 评论(0) 收藏 举报
分类:

题目描述

Sort a linked list in O(n log n) time using constant space complexity.
题意是在给定时间复杂度内对单链表进行排序。看到这个时间复杂度,第一反应是快速排序和归并排序。下图为主要排序算法的时间复杂度和空间复杂度。
这里写图片描述
归并排序稳定且空间复杂度为O(1),所以选择归并排序的思想解决该问题。

package sxd.learn.java.leetcode;

/**
 * 
 * @author lab 
 * 2016/5/24 
 * sort-list : Sort a linked list in O(n log n) time using
 *         constant space complexity.
 */
public class Leetcode4 {

    public static void main(String[] args) {

    }

    public ListNode sortList(ListNode head) {
        int size = 0;
        ListNode current = head;
        if (head == null || head.next == null)
            return head;
        while (current != null) {
            size++;
            current = current.next;
        }

        ListNode mid = head;
        int mid_size = (size - 1) / 2;
        for (int i = 1; i <= mid_size; i++)
            mid = mid.next;
        ListNode head2 = mid.next;
        mid.next = null;
        ListNode h1 = sortList(head);
        ListNode h2 = sortList(head2);
        ListNode result = merge(h1, h2);

        return result;
    }

    public ListNode merge(ListNode h1, ListNode h2) {
        if (h1 == null)
            return h2;
        if (h2 == null)
            return h1;

        ListNode head, cur, h1_cur = h1, h2_cur = h2;
        if (h1_cur.val < h2_cur.val) {
            head = h1_cur;
            cur = head;
            h1_cur = h1_cur.next;
        } else {
            head = h2_cur;
            cur = head;
            h2_cur = h2_cur.next;
        }

        while (h1_cur != null && h2_cur != null) {
            if (h1_cur.val < h2_cur.val) {
                cur.next = h1_cur;
                h1_cur = h1_cur.next;
            } else {
                cur.next = h2_cur;
                h2_cur = h2_cur.next;
            }
            cur = cur.next;
        }
        if (h1_cur != null)
            cur.next = h1_cur;
        if (h2_cur != null)
            cur.next = h2_cur;

        return head;
    }

}

class ListNode {
    int val;
    ListNode next;

    ListNode(int x) {
        val = x;
        next = null;
    }
}
0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:14508次
    • 积分:720
    • 等级:
    • 排名:千里之外
    • 原创:57篇
    • 转载:8篇
    • 译文:1篇
    • 评论:0条
    文章分类