LeetCode_Insertion Sort List
2014-05-06 20:48
309 查看
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)不同,可能导致操作也就不同,这一点与针对于数组的插入操作不同。
代码中描述的很清楚。
这道题简单,就是使用插入排序的方式对链表进行排序,主要就是链表的基本操作。
需要注意的几点:
每步插入操作存在一下三种情况:
//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; } };
相关文章推荐
- leetcode 147: Insertion Sort List
- LeetCode 之 Insertion Sort List — C++ 实现
- Leetcode155: Insertion Sort List
- 【LeetCode】Insertion Sort List
- leetCode(4):Insertion Sort List
- [Leetcode]Insertion Sort List
- Leetcode Insertion Sort List
- Insertion Sort List--leetcode
- [LeetCode] Insertion Sort List 单向链表插入排序
- leetcode_147题——Insertion Sort List(线性表,插入排序)
- 【leetcode】Insertion Sort List
- LeetCode-Insertion Sort List (Python)
- Java for LeetCode 147 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