练习2——顺序表
//实现顺序表基本功能,然两个顺序表相并
#include <iostream>
#include <stdlib.h>
using namespace std;
typedef int T;
class SeqList{
T *data;
int MaxSize;
int last;
public:
SeqList(int sz);
~SeqList(){delete [] data;}
int Length() const {return last+1;}
int Find(T &x)const ;
void Insert(int i,T &x);
int Delete(T &x);
int IsEmpty(){
return last==-1;
}
int IsFull(){
return last==MaxSize-1;
}
T GetData(int i){
return data[i-1];
}
void SetData(int i,T & x){
if(i>0&&i<last+1){
data[i-1]=x;
}
}
void input();
void output() const ;
};
SeqList::SeqList(int sz) {
if(sz>0){
data=new T[sz];
if(data!=NULL){
MaxSize=sz;
last=-1;
} else{
cerr<<"存储分配错误"<<endl;
exit(1);
}
}
}
int SeqList::Find(T &x) const {
int i=0;
while(i<last&&data[i]!=x){
i++;
}
cout<<"last"<<last<<"Find"<<x<<"i="<<i<<endl;
if(i>=last)
return -1;
else{
return i+1;
}
}
void SeqList::Insert(int i, T &x) {
if(last==MaxSize-1){
cerr<<"无法插入"<<endl;
exit(1);
}
if(i<0||i>last+1){
cerr<<"参数越界"<<endl;
exit(1);
}
last++;
for(int j=last;j>i;j--){
data[j]=data[j-1];
}
data[i]=x;
}
int SeqList::Delete(T &x) {
int i=Find(x)-1;
if(i>=0){last--;
for(int j=i;j<=last;j++){
data[j]=data[j+1];
}
return 1;
}
return 0;
}
void SeqList::input() {
cout<<"请输入元素个数:";
while(1){
cin>>last;
if(last<=MaxSize&&last>0)
break;
cout<<"元素个数有误,范围1~"<<MaxSize-1<<endl;
}
for(int i=0;i<last;i++){
cout<<"请输入第"<<i+1<<"个元素:"<<endl;
cin>>data[i];
}
cout<<"表建立完成"<<endl;
last--;
}
void SeqList::output() const {
for(int i=0;i<=last;i++){
cout<<data[i]<<endl;
}
}
void Union(SeqList &a,SeqList &b){
int n=a.Length();
int m=b.Length();
for(int i=0;i<n;i++){
int temp=a.GetData(i+1);
// cout<<temp<<endl;
if(b.Find(temp)==-1){
cout<<"将要插入"<<temp<<endl;
b.Insert(m-1,temp);
m++;
}
}
// b.output();
}
int main(){
SeqList l1(5),l2(5);
l1.input();
l1.output();
l2.input();
l2.output();
Union(l1,l2);
l2.output();
}