博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
链表的插入排序 Insertion Sort List
阅读量:6864 次
发布时间:2019-06-26

本文共 1496 字,大约阅读时间需要 4 分钟。

  hot3.png

问题:

Sort a linked list using insertion sort.

解决:

① 链表插入排序。

/**

 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution { //46ms
    public ListNode insertionSortList(ListNode head) {
        if(head == null || head.next == null) return head;
        ListNode header = new ListNode(Integer.MIN_VALUE);
        header.next = head;
        ListNode cur = head.next;
        head.next = null;
        while(cur != null){
            ListNode tmp = header;
            while(tmp.next != null && tmp.next.val <= cur.val){
                tmp = tmp.next;
            }
            ListNode next = cur.next;
            cur.next = tmp.next;
            tmp.next = cur;
            cur = next;
        }
        return header.next;
    }
}

② 在discuss中看到的,类似于归并排序,将链表分为前后两个链表,然后通过比较依次插入到链表中。

class Solution {

    public ListNode insertionSortList(ListNode head) {
        if(head == null || head.next == null) return head;
        //链表对折
        ListNode slow = head;//用于表示后半部分
        ListNode fast = head;//用于记数
        ListNode tmp = null;//tmp临时存储(类似pre)
        while(fast != null && fast.next != null){
            tmp = slow;
            slow = slow.next;
            fast = fast.next.next;
        }
        ListNode l2 = insertionSortList(slow);//递归使后半部分有序
        tmp.next = null;//断开链表,将其分为两部分
        ListNode l1 = insertionSortList(head);//递归使前半部分有序
        ListNode header = new ListNode(-1);
        ListNode cur = header;
        //将前半部分和后半部分比较
        while(l1 != null && l2 != null){
            if (l1.val < l2.val) {
                cur.next = l1;
                l1 = l1.next;
            }else{
                cur.next = l2;
                l2 = l2.next;
            }
            cur = cur.next;
        }
        if(l1 != null) cur.next = l1;
        if(l2 != null) cur.next = l2;
        return header.next;
    }
}

转载于:https://my.oschina.net/liyurong/blog/1563431

你可能感兴趣的文章
阿里云服务器拼团购,拉上小伙伴立享¥234/年
查看>>
【转】浅谈php://filter的妙用
查看>>
Docker安装Mysql服务
查看>>
阿里云Redis账号
查看>>
跟我学习php文件和目录常用函数-下篇
查看>>
阿里云云盾-风险识别-增强版模式发布
查看>>
赛灵思CEO Victor Peng:中国AI市场创新速度令人振奋,但初创企业应避免扎堆做AI芯片...
查看>>
Spring Security OAuth 2开发者指南译
查看>>
Linking Containers Together
查看>>
Firefox beta 开始原生支持 Windows 10 ARM64
查看>>
区块链技术没那么复杂,别被大佬们忽悠晕了
查看>>
SpringBoot自定义错误页面
查看>>
OneGame V1.0.2 发布,让运营游戏不再是梦想
查看>>
如何使用Lombok来优雅的编码
查看>>
zookeeper安装
查看>>
Java中如何实现序列化,有什么意义?
查看>>
你不知道的console.log
查看>>
手把手教你如何进行FileZilla的安装
查看>>
第一篇开发总结
查看>>
《JavaScript快速全栈开发》作者Azat Mardanov:现在是拥抱Node技术栈的最佳时机
查看>>