LeetCode_Insertion Sort List
来源:互联网 发布:mac如何下载qq游戏 编辑:程序博客网 时间:2024/05/17 06:08
Sort a linked list using insertion sort.
这道题简单,就是使用插入排序的方式对链表进行排序,主要就是链表的基本操作。
需要注意的几点:
每步插入操作存在一下三种情况:
//case 1:if position is head
//case 2:position is not pCurrent
//case 3:position is between head and pCurrent
也就是说需要插入的位置(position)不同,可能导致操作也就不同,这一点与针对于数组的插入操作不同。
代码中描述的很清楚。
class Solution {public: ListNode *insertionSortList(ListNode *head) { if (head==NULL) { return NULL; } if (head->next==NULL) { return head; } //insert sort ListNode* pCurrent; ListNode* pPreCurrent; pPreCurrent=head; pCurrent=head->next; while (pCurrent!=NULL) { ListNode* pPreCompare=NULL; ListNode* pCompare=head; //find position while (pCompare!=pCurrent) { if (pCompare->val>pCurrent->val) { break; } pPreCompare=pCompare; pCompare=pCompare->next; } //case 1:if position is head if (pCompare==head) { //cut the pCurrent pPreCurrent->next=pCurrent->next; //change head and insert pCurrent->next=head; head=pCurrent; //change next pCurrent pCurrent=pPreCurrent->next; } else { //case 2:position is not pCurrent if (pCompare==pCurrent) { //change pCurrent and pPreCurrent pPreCurrent=pCurrent; pCurrent=pCurrent->next; } else { //case 3:position is between head and pCurrent //cut pCurrent pPreCurrent->next=pCurrent->next; //insert pCurrent to position pCurrent->next=pCompare; pPreCompare->next=pCurrent; //change next pCurrent pCurrent=pPreCurrent->next; } } } return head; }};
0 0
- Leetcode_Insertion Sort List
- Leetcode_insertion-sort-list
- LeetCode_Insertion Sort List
- LeetCode_Insertion Sort List
- leetcode_Insertion Sort List
- list sort
- list sort
- Sort List
- Sort List
- list - sort
- Sort List
- Sort List
- Sort List
- Sort List
- Sort List
- Sort List
- Sort List
- Sort List
- div文字水平垂直居中
- cocos2d-x创建第一个项目
- 从茶叶蛋到互联网思维
- unity3d 学习笔记(一)
- hdu4811
- LeetCode_Insertion Sort List
- 解决adb server is out of date. killing...问题
- XCode5.1出现“could not build module XXX”的情况
- 自写jQuery插件,实现简单网页遮罩层/弹出层功能,兼容IE6、IE7
- OOP中的多态
- c++学习杂项
- 利用斯坦福主题模型工具(stanford TMT)做LDA
- cha
- GridLayout 简单实例