C++实现有序表--顺序表的合并操作代码


#include<iostream>
#include<cstdlib>//C++动态分配存储空间
using namespace std;
#define OK 1
#define ERROR 0
#define MAXSIZE 100
typedef int Elemtype;
typedef int Status;
//顺序表的存储结构,结构体类型
typedef struct
{
Elemtype* elem;//动态开辟存储空间
int length;//当前数组的长度
}Sqlist;//顺序表结构类型为Sqlist
Status Initlist(Sqlist& L);//初始化顺序表
Status Createlist(Sqlist& L, int n);//创建顺序表
Status Mergelist(Sqlist La, Sqlist Lb, Sqlist& Lc);//归并La和Lb得到新的顺序有序表Lc
Status Printlist(Sqlist L);//顺序表打印
int main(void)
{
Sqlist La, Lb, Lc;
Initlist(La);
Initlist(Lb);
Initlist(Lc);
int a = 0;
int b = 0;
cout << "输入创建顺序表La的长度:";
cin >> a;
Createlist(La, a);
cout << "输入创建顺序表Lb的长度:";
cin >> b;
Createlist(Lb, b);
Mergelist(La, Lb, Lc);
Printlist(Lc);
return 0;
}
Status Initlist(Sqlist& L)//初始化顺序表
{
L.elem = new Elemtype[MAXSIZE];//为顺序表分配一个数组空间
if (!L.elem) exit(OVERFLOW);
L.length = 0;
return OK;
}
Status Createlist(Sqlist& L, int n)//创建顺序表
{
Elemtype e;
cout << "输入顺序表的数据:";
for (int i = 0; i < n; i++)
{
cin >> e;
L.elem[i] = e;
L.length++;
}
cout << "创建顺序表成功。" << endl;
return OK;
}
Status Mergelist(Sqlist La, Sqlist Lb, Sqlist& Lc)
{
int m = La.length;
int n = Lb.length;
Lc.length = m + n;//新表长度为两个表的长度之和
Lc.elem = new Elemtype[Lc.length];//给新表分配一个数组空间
int* pa, * pb, * pc;
pa = La.elem, pb = Lb.elem, pc = Lc.elem;//指针分别指向三个数组的的首地址
int* pa_last, * pb_last;
pa_last = La.elem + La.length - 1;//pa_last指向La的最后一个元素
pb_last = Lb.elem + Lb.length - 1;//pb_last指向Lb的最后一个元素
while (pa <= pa_last && pb <= pb_last)//都没有达到表位
{
if (*pa <= *pb)//指向La表的所在元素小与或等于指向Lb表的所在元素
{
*pc = *pa;
pc++;
pa++;//*pc++=*pa++;
}
else
{
*pc = *pb;
pc++;
pb++;//*pc++=*pb++;
}
}
while (pa <= pa_last)//La未达到表尾,Lb已到达表尾
{
*pc++ = *pa++;
}
while (pb <= pb_last)//Lb未达到表尾,La已到达表尾
{
*pc++ = *pb++;
}
return OK;
}
Status Printlist(Sqlist L)//顺序表打印
{
cout << "顺序表的值顺序输出为:";
for (int i = 0; i < L.length; i++)
{
cout << L.elem[i] << " ";
}
return OK;
}

posted @ 2023-01-05 17:00  师大无语  阅读(256)  评论(0编辑  收藏  举报