//该程序实现了线性表的顺序存储结构和各项操作,并实现了两个无序集合A、B的并集,并将结果存放到A中,A=A并B
#include<iostream>
using namespace std;
//****线性表和一些基础的定义*****
//线性表的最大长度
#define MAXSIZE 20
#define ElemType int /*表中数据元素类型*/
typedef struct {
ElemType data[MAXSIZE];
int length;
}SqList;
#define OK 1
#define ERROR 0
#define TRUE 1
#define FALSE 0
typedef int Status; //Status为函数类型,其值是函数结果状态代码,如OK等
//初始化线性表
void InitList(SqList* L) {
L->length = 0;
}
//判断线性表是否为空
Status ListEmpty(SqList* L) {
return (L->length==0);
}
//返回线性表元素个数
Status ListLength(const SqList* L) {
return L->length;
}
//获得表中第i个元素
Status GetElem(const SqList* L,int i,ElemType &e) {
if (i<1 || i>L->length) return FALSE;
e = L->data[i-1];
return i;
}
//查找值为e的元素,存在则返回位置,不存在则返回0
Status LocateElem(const SqList* L, const int e) {
for (int i = 0; i <L->length; i++)
{
if (L->data[i] == e)
return i+1;//位置下标从1开始,数组下标从0开始
}
return 0;
}
//向线性表中第i个位置插入一个元素,插入成功则返回位置值,插入失败返回0
Status InsertElem(SqList* L,int i, const int e) {
if (i<1|| i>L->length+1|| L->length>=MAXSIZE)
{
cout << "Out of range!" << endl;
return FALSE;
}
if (i == L->length+1)
{
++L->length;
L->data[L->length - 1] =e;
return i;
}
else {
L->length++;//记住长度+1
for (int j = L->length - 1; j > i - 1; j--)
{
L->data[j] = L->data[j - 1];
}
L->data[i - 1] = e;
return i;
}
}
//从线性表中第i个位置删除一个元素,删除成功则返回所删除位置,否则返回0
Status DeleteElem(SqList* L, int i) {
if (i<1|| i>L->length)
{
cout << "Out of range!" << endl;
return FALSE;
}
if (i == L->length) {
//L->data[L->length - 1] = 0;
L->length--;
return i;
}
for (int j =i-1; j< L->length-1;j++)
{
L->data[j] = L->data[j + 1];
}
L->length--;//记住长度-1
return i;
}
void Union(SqList* LA, const SqList* LB) {
Status LA_len = ListLength(LA);
Status LB_len = ListLength(LB);
ElemType e;
for (int i = 1; i <= LB_len; i++)//注意,获取第几个位置的元素,i从1开始
{
GetElem(LB,i,e);
if (LocateElem(LA,e)== 0) {
InsertElem(LA, LA_len+1,e);//注意,长度先加1,再使用
}
}
}
int main() {
//申请线性表内存空间
SqList *LA= new SqList;
if (LA== 0)
cout << "alloc failed!" << endl;
SqList *LB = new SqList;
if (LB == 0)
cout << "alloc failed!" << endl;
//初始化LA
LA->length = 6;
int a[6]={1,6,3,5,4,2};
for (int i = 0; i < LA->length; i++)
{
LA->data[i] = a[i];
}
//for (int i = 0; i < LA->length; i++)//测试输出LA内容
//{
// cout << LA->data[i] << endl;
//}
//初始化LB
LB->length =4;
int b[4] = { 6,8,11,4};
for (int i = 0; i < LB->length; i++)
{
LB->data[i] =b[i];
}
//for (int i = 0; i < LB->length; i++)//测试输出LB内容
//{
//cout << LB->data[i] << endl;
//}
/*
//以下为测试各函数的代码
//ElemType e=2;
//Status n=LocateElem(LA,2);
//GetElem(LB,2,e);
//ElemType m=InsertElem(LA,0,e);
//ElemType m = DeleteElem(LA,7);
//cout <<"m:"<< m << endl;
*/
Union(LA,LB);//LA和LB中的数据作并运算,结果存于LA中
for (int i = 0; i < LA->length; i++)//输出运算后LA中的值
{
cout << LA->data[i] << endl;
}
delete LA;
delete LB;
system("pause");
return 0;
}
数据结构-线性表的顺序存储实现及各种操作代码
最新推荐文章于 2023-03-24 17:29:40 发布