您的位置:首页 > 其它

Insertion Sort List

2015-09-24 21:14 381 查看
用插入排序对链表排序

您在真实的面试中是否遇到过这个题?

Yes

样例

Given
1->3->2->0->null
,
return
0->1->2->3->null

/**
* Definition of ListNode
* class ListNode {
* public:
*     int val;
*     ListNode *next;
*     ListNode(int val) {
*         this->val = val;
*         this->next = NULL;
*     }
* }
*/
class Solution {
public:
/**
* @param head: The first node of linked list.
* @return: The head of linked list.
*/
ListNode *insertionSortList(ListNode *head) {
// write your code here
if(head==NULL||head->next==NULL) return head;
ListNode *dummy=new ListNode(-1);
dummy->next=head;
ListNode* pre=head;
ListNode *cur=head->next;
while(cur){
if(cur->val>=pre->val){
pre=pre->next;

}else{
pre->next=cur->next;
ListNode *restart=dummy;
while(cur->val>=restart->next->val){
restart=restart->next;
}
cur->next=restart->next;
restart->next=cur;
}
cur=pre->next;
}
return dummy->next;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: