LeetCode - Insertion Sort List
2014-01-14 22:13
288 查看
Insertion Sort List
2014.1.14 21:58
Sort a linked list using insertion sort.
Solution:
Everyone must've have learned about insertion sort on some data structure textbooks, like "Data Structures & Algorithm Analysis". They usually present you with source code for insertion sort on arrays. In this problem, you're required to sort a linked list in a similar manner.
For each list node, use linear search to find the position where it should be inserted. Some boundary conditions need extra code to process, do it carefully.
Time complexity is O(n^2), space complexity is O(1).
Accepted code:
2014.1.14 21:58
Sort a linked list using insertion sort.
Solution:
Everyone must've have learned about insertion sort on some data structure textbooks, like "Data Structures & Algorithm Analysis". They usually present you with source code for insertion sort on arrays. In this problem, you're required to sort a linked list in a similar manner.
For each list node, use linear search to find the position where it should be inserted. Some boundary conditions need extra code to process, do it carefully.
Time complexity is O(n^2), space complexity is O(1).
Accepted code:
class Solution { public: ListNode *insertionSortList(ListNode *head) { if(nullptr == head){ return head; } ListNode *ptr, *root; ListNode *p1, *p2; root = head; head = head->next; root->next = nullptr; while(head != nullptr){ p1 = head->next; ptr = root; if(head->val <= root->val){ head->next = root; root = head; }else{ while(ptr->next != nullptr){ if(head->val >= ptr->val && head->val <= ptr->next->val){ break; }else{ ptr = ptr->next; } } p2 = ptr->next; ptr->next = head; head->next = p2; } head = p1; } // 1WA here, not head = root->next; head = root; return head; } };
相关文章推荐
- [LeetCode] Insertion Sort List
- LeetCode: Insertion Sort List [147]
- LeetCode :: Insertion Sort List [具体分析]
- (Leetcode 147)Insertion Sort List
- [leetcode] Insertion Sort List(python)
- 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 】 python 实现
- Leetcode: Insertion Sort List
- [leetcode] Insertion Sort List
- Leetcode 147 Insertion Sort List
- Leetcode: Insertion Sort List
- Leetcode Insertion Sort List 解题报告
- leetcode:Insertion Sort List