leetcode 链表 排序

1、Sort List
链接:https://leetcode.com/problems/sort-list/
思路:使用归并排序。拆分、合并均采用递归方式。

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

2、Insertion Sort List
链接:https://leetcode.com/problems/insertion-sort-list/
思路:新建一个头指针,直接插入排序

    public ListNode insertionSortList(ListNode head) {
        if(head == null || head.next == null)
            return head;
        ListNode newhead = new ListNode(-1), temp, pre;
        newhead.next = head;
        temp = head;
        pre = temp.next;
        while(pre != null){
            if(pre.val > temp.val){
                temp = pre;
                pre = pre.next;
            }else{
                ListNode fast = newhead.next;
                ListNode low = newhead;
                while(fast.val < pre.val){
                    low = fast;
                    fast = fast.next;
                }
                low.next = pre;
                temp.next = pre.next;
                pre.next = fast;
                pre = temp.next;
            }
        }
        return newhead.next;
    }

3、Reorder List
链接:https://leetcode.com/problems/reorder-list/
思路:将链表后半段翻转,前半段、后半段交替输出

 public void reorderList(ListNode head) {
        if(head == null || head.next == null)
            return;
        ListNode p = head, q = head, r = head;
        while(q != null && q.next != null){
            r = p;
            p = p.next;
            q = q.next.next;
        }
        p = r.next;
        while(p.next != null){
            q = p.next;
            p.next = q.next;
            q.next = r.next;
            r.next = q;
        }
        ListNode s,t;
        t = r.next;
        r.next = null;
        s = head;
        while(s != null && s.next != null){
            p = s.next;
            q = t.next;
            s.next = t;
            t.next = p;
            s = p;
            t = q;
        }
        s.next = t;
    }
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值