标签:元素 不能 位置 存在 数据查询 struct maxsize 插入 没有
顺序表基本操作的实现,主要包括顺序表的初始化、建立、输出、插入、删除、位置查询、数据查询。
#include<iostream.h>
#define MAXSIZE 100
typedef int elemtype;
typedef struct
{
elemtype *data;
int length;
}SequenList; //后面的逗号一定不能省略,这是初学者很容易犯的错误
这一段是对结构体的定义,此处省略了struct后面的结构体名称,这是因为在大括号里没有指向本类型的指针。
//顺序表的初始化
void Init_SequenList(SequenList &L)
{
L.data=new elemtype[MAXSIZE]; //申请分配内存空间
if(!L.data)
cout<<"空间分配失败!\n";
else
{
cout<<"空间分配成功!\n";
L.length=0;
}
}
//顺序表的建立
void Creat_SequenList(SequenList &L)
{
cout<<"顺序表建立成功\n请输入表长:";
cin>>L.length;
cout<<"表中元素为:";
for(int i=0;i<L.length;i++)
cin>>L.data[i]; //这里比较容易出现错误,要记得后面的一维数组
}
//顺序表的输出
void Print_SequenList(SequenList &L)
{
for(int i=0;i<L.length;i++)
{
cout<<L.data[i]<<‘\t‘;
}
cout<<endl;
}
//顺序表数据的插入
void Insert_SequenList(SequenList &L,int i,elemtype x)
{
if(i<0||i>L.length)
cout<<"位置不合理"<<endl;
else
if(L.length==MAXSIZE)
cout<<"表满"<<endl;
else
{
for(int j=L.length-1;j>=i;j--)
L.data[j+1]=L.data[j]; //这里不大好理解,可以画图理解
L.data[i]=x;
L.length++;
}
Print_SequenList(L);
}
//顺序表数据的删除
void Delete_SequenList(SequenList &L,int i)
{
if(i<0||i>L.length-1)
cout<<"位置不合理"<<endl;
else
if(L.length==0)
cout<<"空表"<<endl;
else
{
for(int j=i+1;j<L.length;j++)
L.data[j-1]=L.data[j];
L.length--;
}
Print_SequenList(L);
}
//顺序表对数据的位置寻找
void Getelem_SequenList(SequenList &L,int i,elemtype &e)
{
if(i<0||i>L.length-1)
cout<<"查找的位置不存在"<<endl;
else
{
e=L.data[i];
cout<<e<<endl;
}
}
//顺序表对数据的查找
int Search_SequenList(SequenList &L,elemtype e)
{
for(int i=0;i<L.length;i++)
if(L.data[i]==e)
return i+1;
return 0;
}
main函数的实现
void main()
{
SequenList L;
Init_SequenList(L);
Creat_SequenList(L);
Print_SequenList(L);
int i;
elemtype x;
cout<<"请输入插入的位置和元素:";
cin>>i>>x;
Insert_SequenList(L,i,x);
cout<<"请输入删除的位置:";
cin>>i;
Delete_SequenList(L,i);
elemtype e;
cout<<"请输入查找的位置:";
cin>>i;
Getelem_SequenList(L,i,e);
cout<<"请输入查找的元素:";
cin>>e;
if(!Search_SequenList(L,e))
cout<<"输入的元素"<<e<<"不在顺序表中"<<endl;
else
cout<<"输入的元素"<<e<<"在顺序表的第"<<Search_SequenList(L,e)<<"位中"<<endl;
}
值得注意的是,有一定C/C++基础的同学可以复习一下指针的知识,会给你带来惊喜哦!
标签:元素 不能 位置 存在 数据查询 struct maxsize 插入 没有
原文地址:http://www.cnblogs.com/ye--zi/p/7691273.html