#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(SqList &L)
{
L.elem = new ElemType[100]; //为表分配空间
// if(!L.elem) exit(OVERFLOW); //存储分配失败
L.length=0; //更新空表的长度为0
return OK;
}
//表长,即表中元素
int Length(SqList &L)
{
return L.length;
}
//按值查找
int LocateELem(SqList &L, ElemType &e)
{
for(int i = 0; i < L.length; i++)
{
if(L.elem[i] == e)
return i+1;
}
return 0;
}
//按位查找
int GetElem(SqList &L, int i, ElemType &e)
{
if(i < 1 || i > L.length) return ERROR;
e = L.elem[i-1];
return OK;
}
//插入操作
Status ListInsert(SqList &L, int i, ElemType &e)
{
if(i < 1 || i >= L.length) return ERROR;
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;
L.length++;
return OK;
}
//删除操作
Status ListDelete(SqList &L, int i)
{
if(i < 1 || i >= L.length) return ERROR;
if(L.length==0) return ERROR;
for(int j = i; j<L.length;j++)
{
L.elem[j-1] = L.elem[j];
}
L.length--;
return OK;
}
//输出操作
void PrintList(SqList &L)
{
for(int i = 0; i < L.length; i++)
{
cout<<L.elem[i]<<" ";
}
cout<<endl;
}
//判断是否为空
bool Empty(SqList &L)
{
if(L.length) return true;
return false;
}
int main()
{
/*第一步 创建结构体变量,进行初始化*/
SqList L;
int Init_flag = InitList(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:";
PrintList(L);
/*第三步 按照位置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(L,Insert_i,Insert_value);
if(Insert_flag)
{ //插入成果循环输出L中元素
cout<<"Insert OK!"<<endl;
cout<<"SqList L Length is:"<<L.length<<endl;
PrintList(L);
}
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(L,delete_i);
if(delete_flag)
{
//删除成功
cout<<"delete Ok!"<<endl;
cout<<"SqList L Length is:"<<L.length<<endl;
PrintList(L);
}
return 0;
}
顺序表
最新推荐文章于 2022-06-16 23:42:57 发布