您的位置:首页 > 其它

LeetCode-Insertion Sort List

2013-11-18 15:47 423 查看
Sort a linked list using insertion sort.

/**
* Definition for singly-linked list.
* struct ListNode {
*     int val;
*     ListNode *next;
*     ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode *insertionSortList(ListNode *head) {
// IMPORTANT: Please reset any member data you declared, as
// the same Solution instance will be reused for each test case.
if(head==NULL)return NULL;
if(head->next==NULL)return head;
ListNode* ret=head;
ListNode* ptr,*tmp;
head=head->next;
ret->next=NULL;//Don't forget this one!
while(head!=NULL){
if(head->val<ret->val){
ptr=head->next;
head->next=ret;
ret=head;
head=ptr;
}
else{
ptr=ret;
while(ptr->next!=NULL&&ptr->next->val<head->val){
ptr=ptr->next;
}
tmp=head->next;
head->next=ptr->next;
ptr->next=head;
head=tmp;
}
}
return ret;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: