leetcode Insertion Sort List
2015-03-21 18:31
281 查看
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode *insertionSortList(ListNode *head) { if(head == NULL){ return head; } ListNode* tmp = head; int len = 1; while(tmp->next){ tmp = tmp->next; len++; } ListNode* rec = head->next; ListNode* prev; ListNode dummy(-1); dummy.next = head; ListNode* prevrec = head; for(int i = 1; i < len; ++i){ tmp = rec; ListNode* iter = dummy.next; prev = &dummy; bool insert = false; while(iter != tmp){ if(iter->val > tmp->val){ if(iter->next == tmp){ int swint = tmp->val; tmp->val = iter->val; iter->val = swint; rec = tmp->next; prevrec = tmp; } else{ //insert tmp between prev and iter //prevrec remains unchanged rec = tmp->next; prev->next = tmp; tmp->next = iter; prevrec->next = rec; } insert = true; break; } else{ prev = iter; iter = iter->next; } } if(!insert){ rec = tmp->next; prevrec = tmp; } } return dummy.next; } };
相关文章推荐
- 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 147 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
- 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 解题报告