#include<iostream>
using namespace std;
#define MAXSIZE 100
#define OK 1
#define ERROR 0
#define OVERFLOW -2
typedef int ElemType;
typedef int Status;
typedef struct{
ElemType *elem;
int length;
}SqList;
Status InitList_Sq(SqList &L) //构造一 个空的顺序表L
{
L.elem=new ElemType[MAXSIZE]; //为顺序表分配空间
if(!L.elem) exit(OVERFLOW); //存储分配失败
L.length=0; //空表长度为0
return OK;
}
int GetElem(SqList L,int i,ElemType &e)
{
if (i<1||i>L.length) return ERROR;
//判断i值是否合理,若不合理,返回ERROR
e=L.elem[i-1]; //第i-1的单元存储着第i个数据
return OK;
}
int LocateELem(SqList L,ElemType e)
{
for (int i=0;i< L.length;i++)
if (L.elem[i]==e) return i+1;
return 0;
}
Status ListInsert_Sq(SqList &L,int i ,ElemType e)
{
if(i<1 || i>L.length+1) return ERROR; //i值不合法
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; //将新元素e放入第i个位置
++L.length; //表长增1
return OK;
}
/*删除运算*/
Status ListDelete_Sq(SqList &L,int i)
{
if((i<1)||(i>L.length)) return ERROR; //i值不合法
for (int j=i;j<=L.length-1;j++)
L.elem[j-1]=L.elem[j]; //被删除元素之后的元素前移
--L.length; //表长减1
return OK;
}
int main()
{
/*第一步 创建结构体变量,进行初始化*/
SqList L;
int Init_flag=InitList_Sq(L);
cout<<"第一步 创建结构体变量,进行初始化"<<endl;
if(Init_flag==1)
cout<<"Init OK!"<<endl;
else
cout<<"Init ERROE!"<<endl;
/*第二步 给顺序表赋值*/
cout<<"第二步 给顺序表赋值"<<endl;
for(int i=0;i<20;i++)
L.elem[i]=i+100;
L.length=20;
cout<<"The SqList value is:";
for(int j=0;j<20;j++)
cout<<L.elem[j]<<" ";
cout<<endl;
/*第三步 按照位置k取值 */
cout<<"第三步 按照位置k取值"<<endl;
int k,value,getElem_flag;
cout<<"please input SqList getElem_k:";
cin>>k;
getElem_flag=GetElem(L,k,value);
if( getElem_flag==1)
cout<<"获取到的数据为:"<<value<<endl;
else
cout<<"输入的位置越界!"<<endl;
/*第四步 按值e查找,返回位置*/
cout<<"第四步 按值e查找,返回位置"<<endl;
int e,local_flag;
cout<<"please input local value e:";
cin>>e;
local_flag=LocateELem(L,e);
if(local_flag)
cout<<"该元素的位置是:"<<local_flag<<endl;
else
cout<<"没有找到该元素!"<<endl;
/*第五步 插入运算*/
cout<<"第五步 在位置i处插入元素e"<<endl;
int Insert_i,Insert_value,Insert_flag;
cout<<"please input Insert_i:";
cin>>Insert_i;
cout<<"please input Insert_value:";
cin>>Insert_value;
Insert_flag=ListInsert_Sq(L,Insert_i,Insert_value);
if(Insert_flag)
{ //插入成果循环输出L中元素
cout<<"Insert OK!"<<endl;
cout<<"SqList L Length is:"<<L.length<<endl;
for(int h=0;h<L.length;h++)
cout<<L.elem[h]<<" ";
cout<<endl;
}
else
cout<<"Insert ERROR!"<<endl;
/*第六步 删除运算,将表中的第i个元素删除*/
cout<<"第六步 删除运算,将表中的第i个元素删除"<<endl;
int delete_i,delete_flag;
cout<<"please input the delete_i:";
cin>>delete_i;
delete_flag=ListDelete_Sq(L,delete_i);
if(delete_flag)
{
//删除成功
cout<<"delete Ok!"<<endl;
cout<<"SqList L Length is:"<<L.length<<endl;
for(int h=0;h<L.length;h++)
cout<<L.elem[h]<<" ";
cout<<endl;
}
return OK;
}
顺序表操作(初始化、取值、查找、删除、插入)17计科班
最新推荐文章于 2024-03-17 18:37:46 发布