Insertion Sort List Leetcode

时间:2024-01-12 09:19:56

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;
}
};