您的位置:首页 > 其它

[leetcode] Insertion Sort List

2015-06-09 13:35 344 查看
From : https://leetcode.com/problems/insertion-sort-list/
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) {
if(!head || !head->next) return head;
ListNode *index, *cur=head->next, *p, *pre;
ListNode *phead = new ListNode(0);
phead->next = head;
head->next = NULL;
while(cur) {
int val = cur->val;
pre = phead;
index = pre->next;
p = cur->next;
while(index && index->val<=val) {
pre=index;
index=index->next;
}
cur->next = index;
pre->next = cur;
cur = p;
}
head = phead->next;
delete phead;
return head;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: