博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
147. Insertion Sort List
阅读量:7038 次
发布时间:2019-06-28

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

一、题目

  1、审题

  

  2、分析

    给出一个链表,采用插入排序的方式将节点进行排序。

 

二、解答

  1、思路:

    方法一、

      ①、将第一个节点结点作为新的有序链表的开始。指针 node 指向 head, next 指向 head 的下一个元素。

      ②、将 next 值依次与 node 所指链表节点进行比较,并插入合适位置。

      ③、next 依次向后移动,直到所有节点全部插入 node 所指链表,即 next 为 空。

public ListNode insertionSortList(ListNode head) {        if(head == null)            return head;                ListNode node = head;        ListNode next = head.next;        node.next = null;                while(next != null) {            ListNode pre = node;            ListNode cur = node.next;            // next 值比头节点还小            if(pre.val >= next.val) {                ListNode tmp = next.next;                next.next = pre;                node = next;                next = tmp;            }            // next 值比头结点大,找到合适位置插入            else {                while(cur  != null && cur.val < next.val) {                    pre = cur;                    cur = cur.next;                }                pre.next = next;                next = next.next;                pre.next.next = cur;            }        }        return head;    }

 

    方法二、

      新建一个头节点,在头结点中依次插入预原 List 中的节点。 

public ListNode insertionSortList(ListNode head) {        if(head == null)            return head;                ListNode helper = new ListNode(0);        ListNode cur = head;        ListNode pre = helper;        ListNode next = null;                while(cur != null) {            next = cur.next;            //find the right place to insert            while(pre.next != null && pre.next.val < cur.val)                 pre = pre.next;                        //insert between pre and pre.next            cur.next = pre.next;            pre.next = cur;            pre = helper;            cur = next;        }        return helper.next;    }

 

转载于:https://www.cnblogs.com/skillking/p/9779528.html

你可能感兴趣的文章
【转载】说说标准服务器架构(WWW+Image/CSS/JS+File+DB)续测试环境搭建
查看>>
day13-类的重写和类的私有方法
查看>>
cmd 操作命令
查看>>
java.lang.NoSuchMethodError
查看>>
糗事⊙︿⊙
查看>>
前端工程师的未来
查看>>
JDBC原理
查看>>
Firefly distributed模块的原理与twisted中PB远程调用协议
查看>>
php模拟post提交数据,用处很多,可用来网站的采集,登陆等等
查看>>
Gabor学习笔记
查看>>
Python深入02 上下文管理器
查看>>
SELinux
查看>>
Cisco交换机基础命令 + Win Server08 R2 多网卡配置链路聚合
查看>>
Android简单封装类似JQuery异步请求
查看>>
php中的html元素
查看>>
服务器线程与包关系(不断跟新)
查看>>
基于httpcore(httpclient component)搭建轻量级http服务器
查看>>
《林肯传》--[美]戴尔·卡耐基
查看>>
FZU 1686 神龙的难题 (重复覆盖)
查看>>
linux grep命令详解
查看>>