LeeCode 列表排序

题目一 使用的方法对链表进行排序

原题: Sort a linked list in O(n log n) time using constant space complexity.
分析: 复杂度为O(n log n) 的排序第一时间想到的就是归并排序,没啥好分析的,算法过程是递归的进行划分,排序,最后进行合并
代码:

/**
 * Definition for singly-linked list.
 * class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
    public ListNode sortList(ListNode head) {
        //O(nlogn)复杂度的排序 那就是归并排序
        if(head == null || head.next == null){
            return head;
        }

        //获取链表中间点,使用中间点进行划分链表
        ListNode t1 = head;
        ListNode t2 = head;
        while(t2.next != null && t2.next.next != null){
            t1 = t1.next;
            t2 = t2.next.next;
        }

        //t2 为后半段
        t2 = t1.next;
        //head 为前半段
        t1.next = null;

        //递归调用排序
        ListNode s1 = sortList(head);
        ListNode s2 = sortList(t2);

        // merge
        return merge(s1, s2);
    }

    public ListNode merge(ListNode s1, ListNode s2){
        if (s1 == null && s2 == null){
            return null;
        }else if(s2 == null){
            return s1;
        }else if (s1 == null){
            return s2;
        }

        //对两个排好序的链表进行插入排序
        ListNode p = new ListNode(0);
        ListNode head = p;
        while(s1 != null && s2 != null){
            if (s1.val < s2.val){
                p.next = s1;
                s1 = s1.next;
            }else{
                p.next = s2;
                s2 = s2.next;
            }
            p = p.next;
        }

       //对于任一链表中的剩余元素,拼接到p之后
        if(s1 != null){
            p.next = s1;
        }else if(s2 != null){
            p.next = s2;
        }

        return head.next;
    }
}

题目二: 使用插入法对链表进行排序
原题: Sort a linked list using insertion sort.
分析: 复杂度为O(n log n) 的排序第一时间想到的就是归并排序,没啥好分析的,算法过程是递归的进行划分,排序,最后进行合并
代码:

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值