第0周笔记4-顺序表(四):A与B的并集(应用)

it2022-05-05  52

//核心思想 void union_AB(sqList *&La,sqList *Lb){ int La_len = ListLength(La); int Lb_len = ListLength(Lb); for(int i=1;i<=Lb_len;i++){ int e; GetElem(Lb,i,e); if(locateElem(La,e)<0){ ListInsert(La,++La_len,e); } } } #include<iostream> #include<malloc.h> using namespace std; #define Maxsize 50 typedef int ElemType; typedef struct { ElemType data[Maxsize]; int length; }sqList; //函数声明 void CreatList(sqList *&L,ElemType a[],int n); void disList(sqList *L); bool ListEmpty(sqList *L); int ListLength(sqList *L); bool GetElem(sqList *L,int i,ElemType &e); int locateElem(sqList *L,ElemType e); bool ListInsert(sqList *&L,int i,ElemType e); bool ListDelete(sqList *&L,int i,ElemType e); void DestroyList(sqList *&L); //函数定义 //利用数组创建线性表 void CreatList(sqList* &L,ElemType a[],int n){ L = (sqList*)malloc(sizeof(sqList)); for(int i=0;i<n;i++){ L->data[i]=a[i]; } L->length=n; // cout<<"CreatList succ!"<<endl; } //输出线性表 void disList(sqList *L){ if(ListEmpty(L)) return ; for(int i=0;i<L->length;i++){ cout<<(L->data[i])<<" "; } cout<<endl; // cout<<"disList succ!"<<endl; } //判断线性表是否为空 bool ListEmpty(sqList *L){ // cout<<L->length<<"S"; if((L->length)==0){ return true; }else{ return false; } } //求线性表的长度 length int ListLength(sqList *L){ return L->length; } //求某个位置元素的值 bool GetElem(sqList *L,int i,ElemType &e){ if(i<1||i>L->length) return false; e = L->data[i-1]; return true; } //安装元素的值查找位置 int locateElem(sqList *L,ElemType e){ int i=0; while(i<L->length && L->data[i]!=e) i++; if(i>=(L->length)){ return -1; } else { return (i+1); } } //插入元素 bool ListInsert(sqList *&L,int i,ElemType e){ if(i<1||i>L->length+1){ return false; } i--; //移动 for(int j=L->length;j>i;j--){ L->data[j]=L->data[j-1]; } //插入要插入的元素 L->data[i]=e; //表长加1 L->length++; return true; } //删除元素 bool ListDelete(sqList *&L,int i,ElemType e){ if(i<1||i>L->length+1){ return false; } i--; //将顺序表逻辑序号转化为物理序号 //要删除的元素 e=L->data[i]; //移动覆盖 for(int j=i;j<=L->length;j++){ L->data[j]=L->data[j+1]; } //表长减1 L->length--; return true; } //销毁顺序表 void DestroyList(sqList *&L){ free(L); cout<<"释放长度为"<<L->length<<"的顺序表succ!"<<endl; } void union_AB(sqList *&La,sqList *Lb){ int La_len = ListLength(La); int Lb_len = ListLength(Lb); for(int i=1;i<=Lb_len;i++){ int e; GetElem(Lb,i,e); if(locateElem(La,e)<0){ ListInsert(La,++La_len,e); } } } int main() { sqList *La,*Lb; ElemType arr_A[7] = {4,5,6,7,8,9,10}; ElemType arr_B[7] = {1,2,3,4,5,6,7}; CreatList(La,arr_A,7); CreatList(Lb,arr_B,7); cout<<"线性表La:"<<endl; disList(La); cout<<"线性表LB:"<<endl; disList(Lb); union_AB(La,Lb); cout<<"La与Lb并集后:"<<endl; disList(La); cout<<endl; DestroyList(La); DestroyList(Lb); return 0; }


最新回复(0)