LeetCode 147. Insertion Sort List
来源:互联网 发布:mac win7安装盘制作 编辑:程序博客网 时间:2024/05/16 16:00
插入排序,思路是保证指针不变,只移动链表中的值。
1. 遍历链表,在第i次迭代(第i个结点)时,前i-1项已是升序。
此时找到第i项应插入的位置j, 记录j的值为next_value,将i的值赋值给j.
之后把next_value, 以及结点j之后的值都向后移动以为,最终i的值将被i-1的值覆盖。
2. 注意head==NULL的特殊情况。
代码:
class Solution {public: ListNode *insertionSortList(ListNode *head) { // 可以处理head==NULL的情况,因此不用特判。 for (auto i = head; i != NULL; i = i->next) { for (auto j = head; j != i; j = j->next) { if (i->val < j->val) { int next_value = j->val; j->val = i->val; for (auto k = j->next; k != i; k = k->next) { int tmp = k->val; k->val = next_value; next_value = tmp; } i->val = next_value; break; } } } return 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
- (Embedding graph)嵌入图 搜索引擎 技术
- cocos2dX 之CCAnimation/CCAnimate
- 用Maven引入JEE相关的包的方法
- 二项堆、斐波那契堆、Pairing 堆
- 奇偶排序Linux下c 实现
- LeetCode 147. Insertion Sort List
- 交换排序(exchange sorts)算法大串讲
- 选择排序(selection sorts)算法大串讲
- 插入排序(insertion sorts)算法大串讲
- 关于字符编码的各种疑难解答(多方收集整理)
- 归并排序(merge sorts)算法大串讲
- 分布排序(distribution sorts)算法大串讲
- 排序算法群星豪华大汇演
- js原生代码写瀑布流