题目描述
建立顺序表的类,属性包括:数组、实际长度、最大长度(设定为1000)
已知两个递增序列,把两个序列的数据合并到顺序表中,并使得顺序表的数据递增有序
输入
第1行先输入n表示有n个数据,接着输入n个数据,表示第1个序列,要求数据递增互不等
第2行先输入m表示有m个数据,接着输入m个数据,表示第2个序列,要求数据递增互不等
3 11 33 55
5 22 44 66 88 99
输出
顺序表内容包括顺序表的实际长度和数据,数据之间用空格隔开
第1行输出创建后的顺序表内容
8 11 22 33 44 55 66 88 99
#include <iostream>
using namespace std;
#define ok 0
#define error -1
//顺序表定义
class Seqlist
{
int* list;//元素数组
int maxsize;//顺序表最大长度
int size;//顺序表实际长度
public:
Seqlist();
Seqlist(int *list,int size);
~Seqlist();
void add(Seqlist& s);
void listdisplay();
};
Seqlist::Seqlist()
{
maxsize = 1000;
size = 0;
list = new int[maxsize];
}
Seqlist::Seqlist(int* l, int s)
{
size = s;
maxsize = 1000;
list = new int[maxsize];//一定要定义为maxsize,否则会导致溢出
for (int i = 0; i < s; i++)
{
list[i] = l[i];
}
}
Seqlist::~Seqlist()
{
delete[]list;
}
void Seqlist::add(Seqlist &s)
{
int i, j, k;
i = j = k = 0;
Seqlist ss;//放两顺序表合并后的数据
while (i < size && j < s.size)//两者非空
{
if (list[i] < s.list[j])
{
ss.list[k++] = list[i];
i++;
}
else
{
ss.list[k++] = s.list[j];
j++;
}
}
while (i < size)//s已空
{
ss.list[k++] = list[i];
i++;
}
while (j < s.size)//原顺序表已空
{
ss.list[k++] = s.list[j];
j++;
}
ss.size = k;
ss.listdisplay();
}
void Seqlist::listdisplay()
{
cout << size << " ";
for (int i = 0; i < size; i++)
{
cout << list[i] << " ";
}
cout << endl;
}
int main()
{
int n;
cin >> n;
int* list1 = new int[n];
for (int i = 0; i < n; i++)
{
cin >> list1[i];
}
Seqlist seq1(list1, n);
int m;
cin >> m;
int* list2 = new int[m];
for (int i = 0; i < m; i++)
{
cin >> list2[i];
}
Seqlist seq2(list2, m);
seq1.add(seq2);
}