您的位置:首页 > 理论基础 > 数据结构算法

数据结构基础:线性表的应用(1)

2016-10-19 17:10 267 查看
题目:
实现线性表在顺序存储结构下的插入和删除操作。并用该存储结构实现集合A和集合B的并集和交集操作,要求最终结果存储于集合A当中。

应用模型:

线性表(数组存储)

代码:

#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cstring>
using namespace std;
typedef struct{
int data[100];
int length;
}List;

int Find(List &L,int x){
int i=0;
while(i<L.length&&L.data[i]!=x)
i++;
if(i<L.length)
return i;
else
return -1;
}

int Insert(List &L,int x,int i){
if(i<0||i>L.length||L.length==100)
return 0;
else {
for(int j=L.length;j>i;j--)
L.data[j] = L.data[j -1];
L.data[i]=x;
L.length++;
return 1;
}
}

int Delete(List  &L,int x){
int i=Find(L, x);
if(i>=0&&i<L.length){
for (int j=i;j <L.length;j++)
L.data[j]=L.data[j+1];
L.length--;
return 1;
}
return 0;
}

void Union(List &A,List &B){//求并集
for(int i=0;i<B.length;i++){
int x=B.data[i];
int k=Find(A,x);
if(k==-1){
Insert(A,x,A.length);
}
}
}

void Mutural(List &A,List &B ) {//求交集
int n=A.length;
int m=B.length;
int i = 0;
while(i<A.length) {
int x=A.data[i];
int k=Find(B,x);
if(k==-1){
Delete(A,x);
}
else i++;
}
}

void Show(List A){
for(int i=0;i<A.length;i++){
cout<<A.data[i]<<" ";
}
cout<<endl;
}
int main(){
List A,B;
int n1,n2;
printf("集合A的个数:\n");
cin>>n1;
A.length=n1;
for(int i=0;i<n1;i++){
int x;
cin>>x;
A.data[i]=x;
}
printf("集合B的个数:\n");
cin>>n2;
B.length=n2;
for(int j=0;j<n2;j++){
int y;
cin>>y;
B.data[j]=y;
}
getchar();
char c;
cin>>c;
if(c=='U'){
Union(A,B);
if(A.length==0)
cout<<"Error!"<<endl;
Show(A);
}
if(c=='M'){
Mutural(A,B);
if(A.length==0)
cout<<"Error!"<<endl;
Show(A);
}
return 0;
}


PS:开始定义线性表时,有以下不同写法

typedef struct{

    int* data;

    int length;

}List;

该写法只定义数组的存储位置,不限定存储长度,比较经典

上述程序个人使用了一些C++操作,没有malloc等经典操作,重在理解求交集,求并集的思路

难免不足,希望指出

革命尚未成功!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  数据结构 线性表