LeetCode - 147. Insertion Sort List
来源:互联网 发布:333什么意思网络用语 编辑:程序博客网 时间:2024/04/30 05:40
Insertion Sort的思想是逐步将后面的元素插入到前面相应的位置中来,知道了Insertion Sort的这个思想,我们可以将这种方法用到Linked List上面。另外,由于Linked List的头部或许发生改变,所以我们需要使用dummyNode。
总的来说,在这道题目中,我们使用了三个指针,prev,curr和next。其中curr指向我们要插入到前面的元素,prev和prev.next之间是要插入的内容,而next用于存储curr的下一个结点。在每次循环当中,我们将prev从头开始向后移动,直到prev.next == null或者prev.next.val > curr.val,这时prev和prev.next就是我们要将curr插入的位置。
注意这道题目是我们遇到的为数不多的使用dummyNode,但是却没有在开始设置dummyNode.next = head的题目,整体的代码如下:
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */public class Solution { public ListNode insertionSortList(ListNode head) { if(head == null) return head; // corner case ListNode dummyNode = new ListNode(0); // dummyNode ListNode prev = dummyNode; ListNode curr = head; // node to insert ListNode next = null; while(curr != null){ next = curr.next; // Find the right place to insert while(prev.next != null && prev.next.val < curr.val){ prev = prev.next; } // Insert between prev and prev.next curr.next = prev.next; prev.next = curr; prev = dummyNode; curr = next; } return dummyNode.next; }}
知识点:
1. Insertion Sort在Linked List上的实现,这种方法要记住
2. 遇到的为数不多的dummyNode.next并没有在一开始设置为head的题目,需要注意下
0 0
- 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
- 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
- Android引用项目B实现项目A支撑需要解决InflateException问题
- CentOS7安装gtk+2.0和mysql及环境配置
- An Indexed Cube
- 【codeup 1928】日期差值
- CSS3响应式布局总结
- LeetCode - 147. Insertion Sort List
- Objective-C & Sprite Kit太空历险记 : 2. 初级训练营——Objective-C基础(上)
- Nagios-安装与配置
- Oracle数据库查询优化技巧
- AndroidService
- 【codevs 1294】全排列
- iOS开发从入门到精通-- 单行文本UITextField
- 广播
- L1-023. 输出GPLT-PAT团体程序设计天梯赛GPLT