Insertion Sort List Leetcode

Sort a linked list using insertion sort.

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

class Solution {
public:
ListNode* insertionSortList(ListNode* head) {
if (head == nullptr)
return head;
ListNode temp();
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;
}
};
上一篇:github提交代码失败


下一篇:Linux LVS Nginx HAProxy 优缺点