Leetcode Insertion Sort List 解题报告
来源:互联网 发布:女生发型 知乎 编辑:程序博客网 时间:2024/05/02 00:10
http://oj.leetcode.com/problems/insertion-sort-list/
Sort a linked list using insertion sort.
基本分析:用插入排序对一个链表进行排序。
一开始写的时候想套用数组的插入排序,结果发现无法对末节点加上NULL。
对链表进行插入排序的正确方法是:新建一个头节点,遍历原来的链表,对原链表的每个节点找到新链表中适合插入位置的前指针,然后执行插入操作。
这种操作链表的题有一个技巧就是新建一个dummy作为head,然后把数据插入到dummy的链表中,最后返回dummy.next。
重写了一遍,bug free,一次AC了:)
Sort a linked list using insertion sort.
基本分析:用插入排序对一个链表进行排序。
一开始写的时候想套用数组的插入排序,结果发现无法对末节点加上NULL。
对链表进行插入排序的正确方法是:新建一个头节点,遍历原来的链表,对原链表的每个节点找到新链表中适合插入位置的前指针,然后执行插入操作。
这种操作链表的题有一个技巧就是新建一个dummy作为head,然后把数据插入到dummy的链表中,最后返回dummy.next。
重写了一遍,bug free,一次AC了:)
public class Solution { ListNode searchForInsertPos(ListNode head, int val) { ListNode pre = head; ListNode next = head.next; while(next!=null&&next.val<=val) { pre = next; next = next.next; } return pre; } public ListNode insertionSortList(ListNode head) { if(head==null||head.next==null) { return head; } ListNode dummy = new ListNode(-1); dummy.next = null; ListNode new_next; ListNode pre,next; //ListNode iter = head; while(head!=null) { next = head.next; pre = searchForInsertPos(dummy,head.val); new_next = pre.next; head.next = new_next; pre.next = head; head = next; } return dummy.next; }}
0 0
- LeetCode—Insertion Sort List 解题报告
- Leetcode Insertion Sort List 解题报告
- leetCode解题报告之Insertion Sort List
- Leetcode Insertion Sort List 解题报告
- [LeetCode OJ] Insertion Sort List 解题报告
- 【LeetCode】Insertion Sort List 解题报告
- [leetcode] 147. Insertion Sort List 解题报告
- [Leetcode] 147. Insertion Sort List 解题报告
- [LeetCode]Sort List,解题报告
- LeetCode Sort List 解题报告
- Leetcode Sort List 解题报告
- LeetCode 解题报告 Sort List
- LeetCode Sort List 解题报告
- 景岁的Leetcode解题报告:147.Insertion Sort List (Java)
- Insertion Sort List | leetcode
- Leetcode: Insertion Sort List
- [LeetCode] Insertion Sort List
- Leetcode: Insertion Sort List
- WordCount运行解释
- 本学期要写的东西
- 原标题:饭局上,怎么讲政治
- 子串
- linux svn安装配置管理
- Leetcode Insertion Sort List 解题报告
- 在vs2010搭建lua
- 底层框架PhoneGap
- Linux系统下安装oracle _11g_R2 dataguard-physical standby
- linux curl 命令详解,以及实例(转自:http://blog.51yip.com/linux/1049.html)
- expdp和impdp的实践
- 整理Myclipse快捷键
- There's more to mathematics than rigour and proofs (作者:陶哲轩)
- 树莓派远程控制灯