Insertion Sort List

Sort a linked list using insertion sort.

分析:插入排序的过程是从第二个元素开始,将该元素插入到前面已拍好序的序列的正确位置。如果数据结构是单链表,则主要考察单链表的结点移动操作。将一个结点插入到另一个结点的前面,需要这两个结点的previous结点。特别要注意的一点是:如果当前P指针指的结点已经插入了其他地方,那么指针应该移动到的下一个位置将不是p->next而是pre_p->next;如果P指针没有插入到其他位置,那么指针移动的下一个位置是p->next。时间复杂度O(n),空间复杂度O(1)。

 1 class Solution {
 2 public:
 3     ListNode *insertionSortList(ListNode *head) {
 4         if(!head) return NULL;
 5         ListNode * dummy = new ListNode(-1);
 6         dummy->next = head;
 7         ListNode * p = head->next, * pre_p = head;
 8         while(p){
 9             ListNode * fron = dummy;
10             while(fron->next != p && fron->next->val <= p->val) fron = fron->next;
11             if(fron->next != p){
12                 pre_p->next = p->next;
13                 p->next = fron->next;
14                 fron->next = p;
15                 p = pre_p->next;
16             }else {
17                 pre_p = p;
18                 p = p->next;
19             }
20         }
21         return dummy->next;
22     }
23 };

 

posted on 2014-08-20 16:19  Ryan-Xing  阅读(144)  评论(0编辑  收藏  举报