leetcode题解-147. Insertion Sort List
来源:互联网 发布:好的收纳箱 知乎 编辑:程序博客网 时间:2024/05/21 09:39
题意:使用插入排序,将链表的值从小到大排列。
分析:Insertion Sort就是把一个一个元素往已排好序的list中插入的过程。忘记插入排序过程的同学可以看插入排序维基百科
初始时,sorted list是空,把一个元素插入sorted list中。然后,在每一次插入过程中,都是找到最合适位置进行插入。因为是链表的插入操作,需要维护pre,cur和next3个指针。
pre用来发现合适的插入位置,cur指向当前需要被插入的元素,next指向下一个需要被插入的元素。
当sorted list为空以及pre.next所指向的元素比cur指向的元素值要大时,将cur节点插入pre和pre.next之间。。否则,pre指针后移。最后返回dummyhead的next即可。
class Solution { public static ListNode insertionSortList(ListNode head) { if( head == null ){ return head; } ListNode dummy = new ListNode(0); //new starter of the sorted list ListNode cur = head; //the node will be inserted ListNode pre = dummy; //insert node between pre and pre.next ListNode next = null; //the next node will be inserted //not the end of input list 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 = dummy; cur = next; } return dummy.next; } public static void print(ListNode head){ while(head != null){ System.out.println(head.val); head = head.next; } } public static void main(String[] args) { ListNode l1 = new ListNode(3); ListNode l2 = new ListNode(4); ListNode l3 = new ListNode(2); ListNode l4 = new ListNode(1); ListNode l5 = new ListNode(5); l1.next = l2; l2.next = l3; l3.next = l4; l4.next = l5; print(insertionSortList(l1)); }}
阅读全文
0 0
- leetcode题解-147. Insertion Sort List
- LeetCode题解:Insertion Sort List
- 147. Insertion Sort List 题解
- LeetCode Insertion Sort List 最新题解
- LeetCode 题解(41): Insertion Sort List
- LeetCode 147. Insertion Sort List
- [LeetCode]147.Insertion Sort List
- [leetcode] 147.Insertion Sort List
- 147. Insertion Sort List LeetCode
- LeetCode 147. Insertion Sort List
- LeetCode *** 147. Insertion Sort List
- Leetcode 147. Insertion Sort List
- leetcode.147. Insertion Sort List
- leetcode 147. Insertion Sort List
- LeetCode-147.Insertion Sort List
- LeetCode - 147. Insertion Sort List
- [leetcode] 147. Insertion Sort List
- [LeetCode] 147. Insertion Sort List
- 基于Django的微信公众号开发(5) -- 实现消息的接收与发送
- mybatis原理解析---SqlSession运行过程(上)
- ShaderForge插件介绍详解
- 20171219Excel函数(Offset)使用方法记录
- 树的高度
- leetcode题解-147. Insertion Sort List
- DropoutNet: 解决推荐系统中冷启动问题
- Java进阶之路——从初级程序员到架构师,从小工到专家
- 20171213.1
- 源码解析,浅谈spring-data-jpa 中莫名的查询字段不存在问题
- Vim详解
- 如何快速安装Nginx
- 【配置】Elasticsearch安装配置
- 虚拟机和主机ping通与虚拟机连接互联网之间的切换配置方法