Leetcode: Insertion Sort List
2014-11-25 18:51
239 查看
Sort a linked list using insertion sort.
分析:insertion sort是将当前元素插入到已经排好序的元素的适当位置,时间复杂度为O(n^2)。
分析:insertion sort是将当前元素插入到已经排好序的元素的适当位置,时间复杂度为O(n^2)。
class Solution { public: ListNode *insertionSortList(ListNode *head) { if(head == NULL || head->next == NULL) return head; ListNode dummy(-1); dummy.next = head; for(ListNode *prevp = head, *p = head->next; p; p = prevp->next){ //it's worth noting that q starts from dummy.next not head ListNode *prevq = &dummy, *q = dummy.next; while( q != p && q->val <= p->val){ prevq = q; q = q->next; } if(q != p){ prevp->next = p->next; p->next = q; prevq->next = p; }else{ prevp = p; } } return dummy.next; } };
相关文章推荐
- LeetCode 147 Insertion Sort List(链表插入排序)
- leetcode147~Insertion Sort List
- Leetcode:Insertion Sort List
- C实现 LeetCode->Insertion Sort List(排序)(单链表)
- 【Leetcode】Insertion Sort List
- Insertion Sort List 【leetcode】
- [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】【单链表】【147】Insertion Sort List
- 59_leetcode_Insertion Sort List
- LeetCode——Insertion Sort List
- Insertion Sort List Leetcode Python
- (leetcode)Insertion Sort List
- leetcode Insertion Sort List
- (Leetcode 147)Insertion Sort List