LeetCode 147. Insertion Sort List
来源:互联网 发布:专业网络零售商的优势 编辑:程序博客网 时间:2024/04/30 04:26
题目描述:
Sort a linked list using insertion sort.
我们知道插入排序的基本思想, 和我们斗地主时候整理手牌的顺序的方法非常类似, ie, 前 i 个数组成了一个排序后的序列, 当插入第 i + 1 个数的时候, 只需要遍历这个数组找到新元素应该插入的位置, 就可以实现插入排序了。
当然, 由这个插入位置的而不同, 可以引发不同的插入排序方法的变种, 2 分插入排序, 二路插入排序等
关于更多的详细的介绍, 可以参考这篇文章
八大排序算法
下面给出我们的代码:
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */class Solution {public: ListNode* insertionSortList(ListNode* head) { ListNode myhead(0); ListNode * pre = &myhead; ListNode * phead = head; while (phead){ // 找到新元素插入的位置 ListNode * pNewList = myhead.next; ListNode * preNewList = &myhead; while (pNewList){ if (pNewList->val <= phead->val){ pNewList = pNewList->next; preNewList = preNewList->next; } else{ break; } } // insert node ListNode * pInsert = phead; phead = phead->next; preNewList->next = pInsert; pInsert->next = pNewList; } return myhead.next; }};
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
- iOS开发之iOS与js的交互
- 快速掌握Lua 5.3 —— 从Lua中调用C函数
- springMVC—接受参数以及返回参数
- 30套css后台模板,easyui,jquery 网站
- 微信公众帐号开发教程第9篇-解析接口中的消息创建时间CreateTime
- LeetCode 147. Insertion Sort List
- 3823: 定情信物【递推】【线性筛逆元】【带推导过程】
- 正则表达式的JS验证
- 圣思源-张龙-Java SE 第十一讲(面向对象之封装) 续二
- Activity和Service的生命周期(图)
- CGContextRef
- Spring的SimpleAliasRegistry类解析
- Excel快捷键
- MySQL数据库更改用户密码