C. DS单链表--合并

题目描述
假定两个单链表是递增有序,定义并实现以下函数,完成两个单链表的合并,继续保持递增有序
int LL_merge(ListNode *La, ListNode *Lb)
输入

第1行先输入n表示有n个数据,接着输入n个数据
第2行先输入m表示有M个数据,接着输入m个数据

输出
输出合并后的单链表数据,数据之间用空格隔开
输入样例:
3 11 33 55
4 22 44 66 88
输出样例:
11 22 33 44 55 66 88
#include <iostream>
using namespace std;
#define ok 0
#define error -1

class ListNode
{
public:
    int data;
    ListNode* next;
    ListNode()
    {
        next = NULL;
    }
};

class Linklist
{
public:
    ListNode* head;
    int len;
    Linklist()
    {
        head = new ListNode();
        len = 0;
    }
    void LL_intsert(int i, int item)
    {
        ListNode* p = head;
        ListNode* s = new ListNode();
        int j = 0;
        while (p && j < i - 1)
        {
            p = p->next;
            j++;
        }
        if (!p || j > i - 1)
            return;
        s->data = item;
        s->next = p->next;
        p->next = s;
        len++;
    }
    int LL_merge(ListNode* La, ListNode* Lb)    //递增的顺序合并
    {
        Linklist L3;
        ListNode* p = La->next, * q = Lb->next,*Lc;
        Lc = L3.head = La;//L3链表的头结点是La
        while (p && q)        //只要一个为空就会退出循环
        {
            if (p->data <= q->data)
            {
                Lc->next = p;
                Lc = p;
                p = p->next;
            }
            else
            {
                Lc->next = q;
                Lc = q;
                q = q->next;
            }
        }
        Lc->next = p ? p : q; //补上还未遇到空的剩下的链表
        delete(Lb);
        L3.LL_display();
        return ok;
    }

    void LL_display()
    {
        ListNode* p;
        p = head->next;
        while (p)
        {
            cout << p->data << " ";;
            p = p->next;
        }
        cout << endl;
    }
};

int main()
{
    int n, m, item, x;
    Linklist L1,L2;
    ListNode* La = L1.head;
    ListNode* Lb = L2.head;
    cin >> n;
    for (int i = 1; i <= n; i++)
    {
        cin >> item;
        L1.LL_intsert(i, item);
    }
    cin >> m;
    for (int i = 1; i <= m; i++)
    {
        cin >> item;
        L2.LL_intsert(i, item);
    }
    x = L1.LL_merge(La, Lb);
    

    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值