一、顺序表の定义
顺序表是线性表中一种(顺序)存储方式,是指利用一段连续的内存地址来储存线性表的数据元素(data)。在C语言当中,这常使用数组来实现。
二、顺序表の基本操作
由于顺序表的长度通常是可变的,因此通常我们会定义一个较长的数组来保存出数据,同时还需要记录表的长度。
如例:
struct Student
{
int data[100];
int length;
};
其中,data是存放该顺序表结点的一个数组,数组下标范围位0~99;然后,length则是该顺序表的长度了。
定义了存储结构之后,我们就可以开始进行我们以下的一些基本操作了。
1、顺序表的初始化
(1)构造空顺序表
void InitZeroList(Student *l)
{
l->length=0;
}
(2)构造初始数据顺序表
void InitList(Student *l,int number)//初始数据的个数
{
int i;
l->length=number;
for(i=0;i<number;i++)
cin>>l->data[i];
}
2、清除顺序表的内容
清楚顺序表的内容的操作很简单,其实就类似放弃原来的顺序表,置为空顺序表
void clearList(Student *temp)
{
temp->length=0;
}
3、查找
(1)按值查找
因为数组下标是从‘0’开始的,所以我们在返回的时候要+1,当然,有时候要求就是从第‘0’位开始储存数据的,就不用+1了。
int Checknum(Student *temp,int num)
{
int i;
for(i=0;i<temp->length;i++)
if(temp->data[i]==num)
return i+1;
return 0;
}
(2)按位查找
按位查找有两种情况,一种是位置不存在,即超出顺序表的长度的范围;另一种即是位置存在。
bool Checkpos(Student *temp,int pos)
{
if(pos>temp->length||pos<1)
return false;
return true;
}
4、插入数据
bool Insert(Student *temp,int pos,int num)//pos为插入位置,num为插入数据
{
int i;
if(pos<1||pos>temp->length)
return false;
for(i=temp->length;i>=pos;i--) //将pos后面的数据往后挪
{
temp->data[i]=temp->data[i-1];
}
temp->data[pos-1]=num;
temp->length++;
return true;
}
值得注意的就是,在进行插入之前要进行判断,是否可以进行判断动作
5、删除数据
删除数据和插入数据很相似,也有两种形式,一种删除确定位置,另一种删除确定数据。
(1)删除确定位置
判断位置pos的值是否合适,如果合适,则把后面的数据向前移动,并返回true删除成功;否则,返回false。
bool Deletepos(Student *temp,int pos)
{
int i;
if(pos<1||pos>temp->length)
return false;
for(i=pos-1;i<temp->length;i++)
temp->data[i]=temp->data[i+1];
temp->length--;
return true;
}
(2)删除确定数据
从顺序表的开头开始遍历,遇到与确定数据相同的数据就删除,并记下个数,是为了让后面不相同的数据前移以及让顺序表的长度更新。
void Deletenum(Student *temp,int num)
{
int i,tag=0;
for(i=0;i<temp->length;i++)
{
if(temp->data[i]==num)
{
tag++;
}
else
temp->data[i-tag]=temp->data[i];
}
temp->length-=tag;
}
6、输出数据
void show(Student *temp)
{
int i;
for(i=0;i<temp->length;i++)
{
if(i)
cout<<" ";
cout<<temp->data[i];
}
cout<<endl;
}
7、其他:主函数
int main()
{
int number;
Student temp;
cin>>number;//初始顺序表数据个数
InitList(&temp,number);
show(&temp);
int pos,num;
cin>>num;
pos=Checknum(&temp,num);//查找数据是否存在
if(pos)
cout<<"在第"<<pos<<"个位置"<<endl;
else
cout<<"Wrong Number"<<endl;
cin>>pos;//确认位置是否存在
if(Checkpos(&temp,pos))
cout<<"Yes"<<endl;
else
cout<<"No"<<endl;
cin>>pos;
if(Deletepos(&temp,pos))//删除该位置数据是否成功
cout<<"Delete success"<<endl;
else
cout<<"Delete fail"<<endl;
cin>>num;
Deletenum(&temp,num);//删除与num相同的数据
show(&temp);
cin>>pos>>num;
if(Insert(&temp,pos,num))//在第pos个位置插入num
cout<<"Insert success"<<endl;
else
cout<<"Insert fail"<<endl;
show(&temp);
return 0;
}