合并有序链表

102 阅读1分钟

21、合并两个有序链表

将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。

示例 1:

输入:l1 = [1,2,4], l2 = [1,3,4] 输出:[1,1,2,3,4,4]

示例 2:

输入:l1 = [], l2 = [] 输出:[]

示例 3:

输入:l1 = [], l2 = [0] 输出:[0]

1、思路

2、具体实现

#include<iostream>
using namespace std;

//定义链表节点
typedef struct LNode
{
    int val;
    LNode* next;
    LNode(int val) :val(val), next(nullptr) {};
}*LinkList, LNode;
//创建链表
LinkList ListTailInsert(int n)
{
    LNode* dummyHead = new LNode(-1), * r = dummyHead, * s;
    int val;
    while (cin >> val)
    {
        s = new LNode(val);
        r->next = s;
        r = s;
    }
    return dummyHead;
}

class Solution {
public:
    LNode* Merge(LNode* pHead1, LNode* pHead2) {
        LNode* pHead = new LNode(-1); //虚拟头节点
        LNode* cur = pHead; //新链表的尾指针
        while (pHead1 && pHead2) { //有空链表了就退出循环
            if (pHead1->val <= pHead2->val) {
                cur->next = pHead1; //将较小的节点插入
                pHead1 = pHead1->next;
            }
            else {
                cur->next = pHead2;
                pHead2 = pHead2->next;
            }
            cur = cur->next; //始终指向当前尾节点
        }
        cur->next = pHead1 ? pHead1 : pHead2; //将不为空的呢个链表插入的新链表尾部
        return pHead->next; //返回真正的头指针
    }
};

int main()
{
    LinkList L1,L2;
    LinkList L3;
    ListTailInsert(3);
    ListTailInsert(3);
    Solution s1;
    LinkList res = s1.Merge(L1, L2);
    LNode* cur = res;
    cout << "合并后的链表:";
    while (cur)
    {
        cout << cur->val << " ";
        cur = cur->next;
    }
    return 0;
}