148. Sort List 给链表排序

29 篇文章 0 订阅
13 篇文章 0 订阅

题目描述:

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

Example 1:

Input: 4->2->1->3
Output: 1->2->3->4

Example 2:

Input: -1->5->3->4->0
Output: -1->0->3->4->5

思路:

让有序的链表作为另外一个链表,让给原来链表中的每个指针加入到新的有序链表中

tips:

为了让插入的时候方便,新链表设置了一个头结点,头结点赋予最小的值(Integer.MIN_VALUE),最后再删去头结点。

 

代码:

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode sortList(ListNode head) {
        if(head ==null ||head.next == null) return head;

        //给list设置成为带头结点的
        ListNode list = new ListNode(Integer.MIN_VALUE);
        list.next=null;

        while(head != null){
            ListNode bei = head;
            head = head.next;
            //找到要插入的位置
            ListNode t = list;
            while (t.next != null){
                if(t.val < bei.val){
                    if(t.next.val >= bei.val){
                        //查在t后面
                        break;
                    }
                    t = t.next;
                }
            }
            bei.next = t.next;
            t.next = bei;

        }
        list = list.next;
        return list;
    }
}

结果显示:时间太慢了,怎么提高效率呢?

思考:因为我的空间复杂度比较低,所以考虑空间换时间

怎么做呢?

有待研究。。。。

归并:

public ListNode sortList(ListNode head) {
    if(head == null || head.next == null){
        return head;
    }
    ListNode newHead = new ListNode(0);
    newHead.next = head;

    ListNode slow = newHead, quick = newHead;

    while(quick != null && quick.next != null){
        slow = slow.next;
        quick = quick.next.next;
    }
    if(quick != null){
        slow = slow.next;
    }

    newHead = head;
    while(head != null && head.next != slow){
        head = head.next;
    }
    if(head != null)
        head.next = null;

    return merge(sortList(newHead),sortList(slow));
}
private ListNode merge(ListNode head1, ListNode head2){
    ListNode newHead = new ListNode(0);
    ListNode resHead = newHead;
    while(head1 != null && head2 != null){
        if(head1.val < head2.val){
            newHead.next = head1;
            head1 = head1.next;
        }else{
            newHead.next = head2;
            head2 = head2.next;
        }
        newHead = newHead.next;
    }
    if(head1 != null){
        newHead.next = head1;
    }
    if(head2 != null){
        newHead.next = head2;
    }
    return resHead.next;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值