在所有的数据结构的种类中,有一种简单顺序存放的表,这种数据结构简单而且很实用,就是顺序表。
顺序表是一种线性聚集。顺序表的特点是为了得到顺序表中所要求的表项,必须从表的第一个表项开始,逐个访问表项,直到找到满足要求的表项为止,也就是说,对于顺序表只能顺序存取。
下面,我用代码实现顺序表的基本操作。
#include <iostream>
using namespace std;
class SeqList
{
public:
SeqList(int MaxSize);
~SeqList(){delete []data;}
int Length()const{return last + 1;}
int Find(int &x)const;
int IsIn(int &x);
int Insert(int &x,int i);
int Remove(int &x);
int Next(int &x);
int Prior(int &x);
int IsEmpty(){return last == -1;}
int IsFull(){return last == MaxSize - 1;}
int Get(int i){return i < 0 || i > last ? NULL : data[i];}
void ChooseConduct();
void ShowList();
private:
int *data;
int MaxSize;
int last;
};
SeqList::SeqList(int sz)
if(sz > 0)
MaxSize = sz;
last = -1;
data = new int[MaxSize];
}
cout<<"请输入顺序表的数值:";
for(int i = 0;i < MaxSize;i++)
cin>>data[i];
last++;
int SeqList::Find(int &x)const
int i = 0;
while(i <= last && data[i] != x)
i++;
if(i > last)
return -1;
else
return i;
int SeqList::IsIn(int &x)
int i = 0,found = 0;
while(i <= last && !found)
if(data[i] != x)
else found = 1;
return found;
int SeqList::Insert(int &x,int i)
if(i < 0 || i > last + 1 || last == MaxSize - 1)
return 0;
for(int j = last;j > i;j--)
data[j] = data[j - 1];
data[i] = x;
return 1;
int SeqList::Remove(int &x)
int i = Find(x);
if(i >= 0)
last--;
for(int j = i;j <= last;j++)
data[j] = data[j + 1];
int SeqList::Next(int &x)
if(i >= 0 && i < last)
return data[i + 1];
int SeqList::Prior(int &x)
if(i > 0 && i <= last)
return data[i - 1];
void SeqList::ShowList()
for(int i = 0;i < last + 1;i++)
cout<<data[i]<<" ";
cout<<endl;
void SeqList::ChooseConduct()
int Choose = 1;
cout<<"1:求顺序表的长度"<<endl;
cout<<"2:查找"<<endl;
cout<<"3:判断是否存在某个数"<<endl;
cout<<"4:插入"<<endl;
cout<<"5:删除"<<endl;
cout<<"6:后继"<<endl;
cout<<"7:前驱"<<endl;
cout<<"8:取值"<<endl;
cout<<"9:判断是否为空"<<endl;
cout<<"10:判断是否为满"<<endl;
cout<<"11:打印顺序表"<<endl;
cout<<"12:退出程序"<<endl;
while(Choose)
cout<<"请输入选择:";
cin>>Choose;
switch(Choose)
case 1:cout<<Length()<<endl;break;
case 2:
int i;
cout<<"please input the number:";
cin>>i;
cout<<Find(i)<<endl;
break;
case 3:
cout<<IsIn(i)<<endl;
case 4:
int Num,Location;
cout<<"please input the number and location:";
cin>>Num;
cin>>Location;
cout<<Insert(Num,Location)<<endl;
case 5:
cout<<Remove(i)<<endl;
case 6:
cout<<Next(i)<<endl;
case 7:
cout<<Prior(i)<<endl;
case 8:
cout<<Get(i)<<endl;
case 9:cout<<IsEmpty()<<endl;break;
case 10:cout<<IsFull()<<endl;break;
case 11:ShowList();break;
default:
cout<<"Bye - Bye!"<<endl;
return;
void main()
SeqList list(5);
list.ChooseConduct();
下面在介绍一下作为抽象数据类型,使用顺序表的事例。
“并”运算和“交”运算:
Void
Union(SeqList &LA,SeqList &LB)
Int n =
LA.Length();
Int m =
LB.Length();
For(int I = 0;I
<
m;i++)
Int x =
LB.Get(i);
Int k =
LA.Find(x);
If(k == -1)
LA.Insert(n +
1,x);
N++;
Insertsection(SeqList &LA,SeqList &LB)
Int I = 0;
While(I <
n
)
{
LA.Get(i);
LB.Find(x);
If(k == -1)
LA.Remove(x);
N--;
Else
I++;
}
因为代码比较简单,所以没有什么注释!