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

2022/3/1 11:21:59

本文主要是介绍[算法] 排序奇升偶降链表,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

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

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


这篇关于[算法] 排序奇升偶降链表的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程