标签:style blog io ar color sp for on div
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; } };
标签:style blog io ar color sp for on div
原文地址:http://www.cnblogs.com/Kai-Xing/p/4121710.html