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

题目:

实现线性表在顺序存储结构下的插入和删除操作。并用该存储结构实现集合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等经典操作,重在理解求交集,求并集的思路

难免不足,希望指出



革命尚未成功!

  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值