您的位置:首页 > 其它

Insertion Sort List Leetcode

2015-12-22 21:44 477 查看
Sort a linked list using insertion sort.

这个题我巧妙的设置了一个临时头结点

class Solution {
public:
ListNode* insertionSortList(ListNode* head) {
if (head == nullptr)
return head;
ListNode temp(0);
temp.next = head;
head = &temp;
ListNode *cur = head->next;
while (cur->next != nullptr)
{
ListNode *back = head;
while (back->next != cur->next && back->next->val <= cur->next->val)
back = back->next;
if (back->next != cur->next)
{
ListNode *now = cur->next;
cur->next = cur->next->next;
now->next = back->next;
back->next = now;
}
else {
cur = cur->next;
}
}
return temp.next;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: