LeetCode题目5:Insertion Sort List
来源:互联网 发布:三星clx3305清零软件 编辑:程序博客网 时间:2024/06/10 19:17
这个题目要求利用插入排序来排序一个单链表。插入排序的思想就是,长度从1开始,逐步增长已排序的序列长度。具体是:每次从未排序的序列中拿出一个元素,插入到已排序序列的正确位置。这个算法复杂度是O(N^2),在单链表中使用插入排序要比在数组中快一些,因为单链表中省去了元素移动这个步骤。
这个题目其实也不是那么容易就过的,写的很快也就10分钟,第一版提交后在数据{3,2,4}出现了RE,坑爹的是同样数据我这边编译器运行明明没有异常。后面很小心的改了两处指针边界判断,就过了。感觉这题用前面mergesort之类代码作弊毫无压力。
P.S. 打算在Git上开一个项目,就叫CrackingLeetCode。估计已经有了类似的?Just for fun。
class Solution {public:ListNode *insertionSortList(ListNode *head) {if (head == NULL)return head;ListNode *newHead = new ListNode(0);newHead->next = head;ListNode *indexNode = head;ListNode *startNode = newHead;while (indexNode->next != NULL){while (startNode->next != indexNode->next){if (startNode->next->val >= indexNode->next->val){ListNode* tmp = startNode->next;startNode->next = indexNode->next;indexNode->next = indexNode->next->next;startNode->next->next = tmp;break;}startNode = startNode->next;}if(startNode->next == indexNode->next)indexNode = indexNode->next;startNode = newHead;}return newHead->next;}};
0 0
- LeetCode题目5:Insertion Sort List
- leetcode题目解答---Insertion Sort List
- LeetCode 5 Insertion Sort List
- Insertion Sort List | leetcode
- Leetcode: Insertion Sort List
- [LeetCode] Insertion Sort List
- Leetcode: Insertion Sort List
- leetcode-Insertion Sort List
- [LeetCode]Insertion Sort List
- 【LeetCode】Insertion Sort List
- LeetCode | Insertion Sort List
- LeetCode - Insertion Sort List
- [LeetCode] Insertion Sort List
- Insertion Sort List (LeetCode)
- [LeetCode] Insertion Sort List
- [LeetCode]Insertion Sort List
- leetcode Insertion Sort List
- Insertion Sort List -- LeetCode
- cytoscape 安装后打开时出现错误:The JVM could not be started.....的解决方式
- vector 容器类 (C++)
- 一个x轴为时间的gnuplot图形绘制
- 1006. Sign In and Sign Out (25)
- Bootstraphero网站搜集了大量关于Bootstrap的开发资源
- LeetCode题目5:Insertion Sort List
- IOS7如何获取设备唯一标识
- 判断当前是手机还是平板
- poj 3661——Running
- 文件操作小结(C语言版)
- URIEncoding意义
- 暴力-Birthday Cake
- spring mvc 接收json、xml 数据格式,自动解析成对象
- Linux中文件查找方法大全