Leetcode: Insertion Sort List
Sort a linked list using insertion sort.
分析: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; } };