实现代码为C语言,教材为清华大学严蔚敏版。
#include<stdio.h>
#include<stdlib.h>
#define OK 1
#define ERROR 0
#define MAXSIZE 100
typedef int Status;
typedef int ElemType;
typedef struct
{
ElemType *elem;//*elem存储空间的基地址
int length;
}Sqlist;
Sqlist L;
Status Initlist(Sqlist &L)//构造一个空的线性表
{
L.elem=new ElemType[MAXSIZE];
if(!L.elem)
return ERROR;
L.length=0;
return OK;
}
int GetElem(Sqlist L,int i,ElemType &e)
{
if(i<1||i>L.length)
return ERROR;
e=L.elem[i-1];//第i-1个单元存储着第i个数据
return OK;
}
//清空线性表
int ClearList(Sqlist &L)
{
L.length=0;
return OK;
}
//判断线性表是否为空
int IsEmpty(Sqlist L)
{
if(L.length==0)
return OK;
}
//获取线性表的长度
int Getlength(Sqlist L)
{
return(L.length);
}
int DestoryList(Sqlist &L)
{
if(L.elem)
delete L.elem;
return OK;
}
Status locateElem(Sqlist &L,ElemType e )
{
int i;
for(i=0;i<L.length;i++)
{
if(L.elem[i]==e)
return i+1;
}
return ERROR;
}
Status ListInsert(Sqlist &L,int i,ElemType e)
{
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;
}
int ListDelete(Sqlist &L,int i)
{
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;
}
//主函数测试
int main()
{
if(Initlist(L))
{
printf("Initlist success!\n");
int i;
ElemType e;
for(i=0;i<10;i++)
{
ListInsert(L,i+1,i);//测试InsertList函数
}
printf("Length is %d\n",Getlength(L));
if(GetElem(L,1,e))
printf("the first element %d\n",e);
else
printf("element is not exist\n");
if(locateElem(L,2))
printf("the element is locate at %d\n",locateElem(L,2));
else
{
printf("the element is not exist");
}
if(ListDelete(L,2))
printf("delect ok");
if(IsEmpty(L))
printf("List is empty");
else
printf("list is not empty");
if(DestoryList(L))
printf("destory success\n");
if(ClearList(L))
printf("clear success");
}
return 0;
}