1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175
| typedef struct { int *elem; int length; }SqList;
int InitList(SqList &L) { L.elem=new ElemType[maxsize]; if(!L.elem) exit(overflow); L.length=0; return ok; }
int ListInsert(SqList &L,int i,int e) { if((i<1)||(i>L.length+1)) return error; //插入位置是否合法的判断 if(L.length==maxsize) return error; for(int j=L.length-1;j>=i-1;j--) L.elem[j+1]=L.elem[j]; //插入后元素位置的移动变化 L.elem[i-1]=e; ++L.length; return ok; } //顺序表元素的获取 int GetElem(SqList L,int i,int &e) { if(i<1||i>L.length) return error; e=L.elem[i-1]; return e; } //判断值是否相等 int EqualList(int a,int b) { if(a==b) return ok; else return error; } //判断顺序表中是否存在值为e的元素 int LocateElem(SqList L,ElemType e,int EqualList(int a, int b)) { int i=1; int *p=L.elem; while(i<=L.length&&!EqualList(*p++,e)) ++i; if(i<=L.length) return 1; else return 0;
} //顺序表的打印 void PrintList(SqList L) { for(int i=0; i<L.length; i++) { cout<<L.elem[i]<<" "; } cout<<endl;
} //顺序表表示集合的并集 void MergeList(SqList LA,SqList LB,SqList & LC) { int m,n,e; m=LA.length;n=LB.length; for(int i=1;i<=n;i++) { GetElem(LB,i,e); //获取B中第i个元素并返回给e if(!LocateElem(LA,e,EqualList) ) { ListInsert(LA,++m,e); //将e插在LC的最后 } } for(int i=1;i<=m;i++) { GetElem(LA,i,e); //获取A中第i个元素并赋给e ListInsert(LC,i,e); }
}
int Mixture(SqList LA,SqList LB,SqList &LC) {//a与b的交集 int m,n,e; m=LA.length; n=LB.length; int j=0; SqList p=m<=n?LA:LB; SqList q=m>n?LA:LB; for(int i=1;i<=p.length;i++) { GetElem(p,i,e); if(LocateElem(q,e,EqualList)) { ListInsert(LC,++j,e); } } if(LC.length) return ok; else return error; }
int Different(SqList LA,SqList LB,SqList &LC) {//求A-B的集合 int m=LA.length; int e; int j=0; for(int i=1;i<=m;i++) { GetElem(LA,i,e); if(!LocateElem(LB,e,EqualList)) ListInsert(LC,++j,e); } if(LC.length) return ok; else return error; }
int main() { SqList LA,LB; InitList(LA); InitList(LB);
cout<<"线性表a的长度:"<<endl; int la; cin>>la; cout<<"请输入a中的元素:"<<endl; int e; for(int i=1;i<=la;i++) { cin>>e; ListInsert(LA,i,e); } cout<<"A中的元素:"<<endl; PrintList(LA); cout<<"线性表b的长度:"<<endl; int lb; cin>>lb; cout<<"请输入b中的元素:"<<endl; for(int i=1;i<=lb;i++) { cin>>e; ListInsert(LB,i,e); } cout<<"B中的元素"<<endl; PrintList(LB);
cout<<"A并B:"; SqList LC1; InitList(LC1); MergeList(LA,LB,LC1); PrintList(LC1);
cout<<"A交B:"; SqList LC2; InitList(LC2); Mixture(LA,LB,LC2); PrintList(LC2);
cout<<"A差B:"; SqList LC3; InitList(LC3); Different(LA,LB,LC3); PrintList(LC3);
return 0; }
|