[算法] 排序奇升偶降链表

字节跳动高频题——排序奇升偶降链表

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;
    }
};
上一篇:数据结构与算法入门教程(C语言实现版)


下一篇:https://www.cnblogs.com/unibo/p/13488447.html