线性表的两个非递减集合求并集

本文介绍了使用C++编写的List结构体,包含插入函数、合并两个列表以及打印功能,展示了如何对整数列表进行操作并合并。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在这里插入图片描述
在这里插入图片描述

#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include<vector>
using namespace std;

#include <iostream>
using namespace std;
struct List 
{
    int _length;
    int _capacity;
    int* _data;

    List(int capacity) 
    {
        _capacity = capacity;
        _length = 0;
        _data = new int[_capacity];
    }

    ~List()
    {
        delete[] _data;
    }
};

bool Insert(List& list, int value) 
{
    //表满--无法插入
    if (list._length == list._capacity)
    {
        return false;
    }
    //插入值比前一个值小 重新输入
    if (list._length > 0 && value < list._data[list._length - 1]) 
    {
        return false;
    }
    //正常插入
    list._data[list._length] = value;
    list._length++;

    return true;
}


List Merge(const List& listA, const List& listB)
{
    List listC(listA._capacity + listB._capacity);
    int i = 0, j = 0;
    while (i < listA._length && j < listB._length) 
    {
        if (listA._data[i] < listB._data[j]) 
        {
            Insert(listC, listA._data[i]);
            i++;
        }
        else 
        {
            Insert(listC, listB._data[j]);
            j++;
        }
    }
    while (i < listA._length) 
    {
        Insert(listC, listA._data[i]);
        i++;
    }
    while (j < listB._length)
    {
        Insert(listC, listB._data[j]);
        j++;
    }

    return listC;
}

void Printf(const List& list) 
{
    for (int i = 0; i < list._length; i++) 
    {
        cout << list._data[i] << " ";
    }
    cout << endl;
}

int main()
{
    int ALen;
    cin >> ALen;

    List listA(ALen);
    for (int i = 0; i < listA._capacity; i++) 
    {
        int value;
        cin >> value;
        if (!Insert(listA, value)) 
        {
            cout << "输入错误,请重新输入该值:";
            i--;
        }
    }

    int BLen;
    cin >> BLen;

    List listB(BLen);
    for (int i = 0; i < listB._capacity; i++) 
    {
        int value;
        cin >> value;
        if (!Insert(listB, value)) 
        {
            cout << "输入错误,请重新输入该值:";
            i--;
        }
    }

    Printf(listA);
    Printf(listB);

    List listC = Merge(listA, listB);
    Printf(listC);

    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

阿猿收手吧!

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值