Sort a linked list using insertion sort.

 

 1 class Solution {
 2 public:
 3     ListNode* insertionSortList(ListNode* head) {
 4         ListNode *newhead=new ListNode(-1);
 5         while(head!=NULL)
 6         {
 7             //保存head位置
 8             ListNode *tmp=head->next;
 9             ListNode *cur=newhead;
10 
11             while(cur->next!=NULL&&cur->next->val<head->val)
12             {
13                 cur=cur->next;
14             }
15             //插入
16             head->next=cur->next;
17             cur->next=head;
18             //恢复head
19             head=tmp;
20         }
21 
22         return newhead->next;
23     }
24 };

 

posted on 2015-05-29 07:45  黄瓜小肥皂  阅读(109)  评论(0编辑  收藏  举报