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

Posted hzy1721

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[算法] 排序奇升偶降链表相关的知识,希望对你有一定的参考价值。

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

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语言算法实现

链表的冒泡排序算法