合并俩个有序单链表

#include "List.h"
using namespace std;

Node* mergeN(Node* head1, Node* head2)
{
    if(head1 == nullptr || head2 == nullptr)
        return head1 == nullptr ? head2 : head1;

    Node* head = head1->value < head2->value ? head1 : head2;
    Node* cur1 = head == head1 ? head1: head2;
    Node* cur2 = head == head1 ? head2 : head1;
    Node* pre = nullptr;
    Node* next = nullptr;
    while(cur1 && cur2)
    {
        if(cur1->value < cur2->value)
        {
            pre = cur1;
            cur1 = cur1->next;
        }
        else
        {
            next = cur2->next;
            cur2->next = cur1;
            pre->next = cur2;
            pre = cur2;
            cur2 = next;
        }
    }
    pre->next = cur1 == nullptr ? cur2 : cur1;
    return head;
}
int main()
{
    Node* pNode0 = new Node(5);
    Node* pNode1 = new Node(4, pNode0);
    Node* pNode2 = new Node(3, pNode1);
    Node* pNode3 = new Node(6);
    Node* pNode4 = new Node(3, pNode3);
    Node* pNode5 = new Node(2, pNode4);

    pNode5 = mergeN(pNode5, pNode2);
    Print(pNode5);
}

猜你喜欢

转载自blog.csdn.net/wzc2608/article/details/80691209
今日推荐