[演算法] 排序奇升偶降連結串列
阿新 • • 發佈:2022-03-01
NC207 排序奇升偶降連結串列
/** * struct ListNode { * int val; * struct ListNode *next; * ListNode(int x) : val(x), next(nullptr) {} * }; */ class Solution { pair<ListNode *, ListNode *> splitOddEvenList(ListNode *head) { if (!head) return {nullptr, nullptr}; ListNode *dummyHead = new ListNode(0); ListNode *prev1 = head; ListNode *prev2 = dummyHead, *curr2 = head->next; while (curr2) { prev1->next = curr2->next; prev2->next = curr2; prev1 = prev1->next; prev2 = curr2; if (!prev1) break; curr2 = prev1->next; } prev2->next = nullptr; ListNode *head2 = dummyHead->next; delete dummyHead; return {head, head2}; } ListNode* reverseList(ListNode *head) { ListNode *prev = nullptr, *curr = head, *next; while (curr) { next = curr->next; curr->next = prev; prev = curr; curr = next; } return prev; } ListNode* mergeSortedList(ListNode *head1, ListNode *head2) { ListNode *dummyHead = new ListNode(0), *prev = dummyHead; ListNode *curr1 = head1, *curr2 = head2; while (curr1 && curr2) { if (curr1->val <= curr2->val) { prev->next = curr1; curr1 = curr1->next; } else { prev->next = curr2; curr2 = curr2->next; } prev = prev->next; } while (curr1) { prev->next = curr1; curr1 = curr1->next; prev = prev->next; } while (curr2) { prev->next = curr2; curr2 = curr2->next; prev = prev->next; } ListNode *head = dummyHead->next; delete dummyHead; return head; } public: /** * 程式碼中的類名、方法名、引數名已經指定,請勿修改,直接返回方法規定的值即可 * * * @param head ListNode類 * @return ListNode類 */ ListNode* sortLinkedList(ListNode* head) { auto [head1, head2] = splitOddEvenList(head); head2 = reverseList(head2); head1 = mergeSortedList(head1, head2); return head1; } };