Insertion Sort List(leetcode)
2014-11-20 16:46
267 查看
题目:
Sort
a linked list using insertion sort.
题目来源:https://oj.leetcode.com/problems/insertion-sort-list/
解题思路:从第一个节点开始,逐步插入到比它大的第一个数前面,把原来的那个节点删除。
Sort
a linked list using insertion sort.
题目来源:https://oj.leetcode.com/problems/insertion-sort-list/
解题思路:从第一个节点开始,逐步插入到比它大的第一个数前面,把原来的那个节点删除。
#include<iostream> using namespace std; struct ListNode { int val; ListNode *next; ListNode(int x) : val(x), next(NULL) {} }; //把second插入到first之后 void insert(ListNode *first,ListNode *second) { ListNode *temp=first->next; first->next=second; second->next=temp; } ListNode *insertionSortList(ListNode *head) { if(head==NULL) return NULL; ListNode *first=new ListNode(INT_MIN); first->next=head; ListNode *curr=head,*prev=first,*prevCurr=first; while(curr!=NULL) { prev=first; ListNode *post=first; while(post!=curr && post->val<curr->val) { prev=post; post=post->next; } if(post!=curr) { prevCurr->next=prevCurr->next->next;//把curr节点删除 insert(prev,curr); curr=prevCurr->next; } else { prevCurr=curr; curr=curr->next; } } return first->next; } int main() { ListNode *head=new ListNode(4); head->next=new ListNode(2); head->next->next=new ListNode(1); head->next->next->next=new ListNode(3); ListNode *result=insertionSortList(head); system("pause"); return 0; }
相关文章推荐
- [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
- The Solution to LeetCode 147 Insertion Sort List
- Leetcode[147]-Insertion Sort List
- leetcode-Insertion Sort List
- 【Leetcode】Insertion Sort List (Sorting)
- 【LeetCode】Insertion Sort List 解题报告
- LeetCode - Insertion Sort List
- LeetCode 147:Insertion Sort List
- Leetcode习题:Insertion Sort List
- Leetcode---Insertion Sort List
- [LeetCode-Algorithms-147] "Insertion Sort List" (2017.12.21-WEEK16)
- Leetcode Insertion Sort List
- 【leetcode】 Insertion_Sort_List