(一)将“顺序表.cpp”中的 main函数填充完整,实现:
1、创建一个顺序表(12 13 21 24 28 30 42 77),从键盘输入各元素的值;
2、查找顺序表里是否有元素28,是否有元素28?
3、输出顺序表中所有元素。
4、在顺序表中第6个位置插入一个元素9,实现顺序表插入的基本操作,输出顺序表中所有元素。
5、在顺序表中删除指定位置(i=4,即是第5个元素)的元素,实现顺序表的删除的基本操作,输出顺序表中所有元素。
#include<iostream>
#include<stdlib.h>
#include<fstream>
#include<string>
#include<iomanip>
using namespace std;
#define OK 1
#define ERROR 0
#define OVERFLOW -2
typedef int Status; //Status 是函数返回值类型,其值是函数结果状态代码。
typedef int ElemType; //ElemType 为可定义的数据类型,此设为int类型
#define MAXSIZE 100 //顺序表可能达到的最大长度
typedef struct {
ElemType *elem; //存储空间的基地址
int length; //当前长度
} SqList;
Status InitList(SqList &L) { //算法2.1 顺序表的初始化
//构造一个空的顺序表L
L.elem = new ElemType[MAXSIZE]; //为顺序表分配一个大小为MAXSIZE的数组空间
if (!L.elem)
exit(OVERFLOW); //存储分配失败退出
L.length = 0; //空表长度为0
return OK;
}
Status GetElem(SqList L, int i, ElemType &e) {//算法2.2 顺序表的取值
if (i<1||i>L.length) return ERROR;
e=L.elem[i-1];
return OK;
//TODO
}
int LocateElem(SqList L, ElemType e) { //算法2.3 顺序表的查找
for (int i=0;i<8;i++)
if (L.elem[i]==e){
cout<<"存在"<<e<<endl;
return i+1;
}
cout<<"无此值"<<endl;
return 0;
}
Status ListInsert(SqList &L, int i, ElemType e) { //算法2.4 顺序表的插入
if((i<1)||(i>L.length+1)) 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;
//在顺序表L中第i个位置之前插入新的元素e
//i值的合法范围是1<=i<=L.length+1
//TODO
}
Status ListDelete(SqList &L, int i) { //算法2.5 顺序表的删除
if((i<1)||(i>L.length)) return ERROR;
for(int j=i;j<=L.length-1;j++)
L.elem[j-1]=L.elem[j];
--L.length;
return OK;
//在顺序表L中删除第i个元素,并用e返回其值
//i值的合法范围是1<=i<=L.length
//TODO
}
Status ShowList(SqList L)
{
for(int i=0;i<L.length;i++)//线性表的输入和输出
cout<<L.elem[i]<<" ";
//依次输出打印顺序表中每个元素
//TODO
}
int main()
{
ElemType i,e;
SqList L;
InitList(L);
for(i=1;i<=8;i++){
cin>>e;
ListInsert(L,i,e);
}
cout<<"顺序表中所有元素为:"<<endl;
ShowList(L);
cout<<endl;
cout<<"请输入需要查找的值:";
cin>>e;
LocateElem(L,e);
cout<<"请输入需要插入的位置:";
cin>>i;
cout<<"请输入需要插入的数:";
cin>>e;
ListInsert(L,i,e);
cout<<"插入后顺序表中所有元素为:"<<endl;
ShowList(L);
cout<<endl;
cout<<"请输入需要删除数值的位置:";
cin>>i;
ListDelete(L,i);
cout<<"删除后顺序表中所有元素为:"<<endl;
ShowList(L);
return OK;
}
运行截图:
想起来CSDN账号密码了