您的位置:首页 > 其它

Insertion Sort List

2014-04-15 22:56 176 查看
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) {
ListNode dummy(INT_MIN);
dummy.next = head;
ListNode* cur = &dummy;
while(cur->next) {
if(cur->next->val >= cur->val)
cur = cur->next;
else
insert(&dummy, cur, cur->next);
}
return dummy.next;
}

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