sort-list(Leetcode)

题目描述

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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值