引言
首先,明确什么是线性表,它是线性结构的,相当灵活,其长度可根据需要增长或缩短,即对线性表的数据元素不仅可以进行访问,而且可以进行插入和删除等操作。
然后顺序表的实现就是用一维数组的形式完成对线性表的表示,逻辑物理上都是相邻的
#include<iostream>
#include<cstdio>
#include<cstdlib>
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;
}
void DestroyList(SqList &L)//
{
if(L.elem)
delete []L.elem; //释放顺序表数组的存储空间
}
int ListLength(SqList L)//计算长度
{
/****在此下面完成代码***************/
return L.length;
/***********************************/
}
bool ListEmpty(SqList L)//判断是否为空
{
/****在此下面完成代码***************/
if(L.length==0)
return OK;
else
return ERROR;
/***********************************/
}
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;
int j=L.length-1;
while(j>=i-1){
L.elem[j+1]=L.elem[j];
j--;
}
L.elem[i-1]=e;
++L.length;
return OK;
/***********************************/
}
void ListPrint(SqList L)//打印顺序表
{
for(int i = 0; i < L.length; i++)
cout << L.elem[i] << ((i == L.length - 1) ? '\n' : ' ');
}
int main()
{
SqList L;
string op;
InitList(L);
while(cin >> op) {
if(op == "Empty")
cout << (ListEmpty(L) ? "Empty" : "Not empty") << endl;
else if(op == "Insert") {
int i, e;
cin >> i >> e;
if(ListInsert(L, i, e) == ERROR)
cout << "Insert failed" << endl;
else
ListPrint(L);
} else if(op == "Length") {
cout << "List length is " << ListLength(L) << endl;
}
}
DestroyList(L);
return 0;
}