线性表的顺序存储结构
1.头文件SqList.h
#define TRUE 1
#define FALSE 0
#define OK 1
#define ERROR 0
#define ElemType int
#define LIST_INIT_SIZE 10
#define LIST_INCREMENT 10
typedef int Status;
typedef struct
{
ElemType *elem;
int length;
int listsize;
}SqList;
Status InitList(SqList &L);//初始化
Status DestoryList(SqList &L);//销毁销毁
Status ClearList(SqList &L);//清空线性表
Status GetElem(SqList L,int i,int &e);//获取线性表中指定位置元素
Status ListInsert(SqList &L,int i,int e);//在指定位置插入元素
Status ListDelete(SqList &L,int i,int &e);//删除指定位置元素,并用e返回值
Status LocateElem(SqList L,int e);//获取元素子啊线性表中的位置
Status ListLength(SqList L);//获取线性表的长度
Status ErgodicList(SqList L);//线性表的遍历
2.函数实现SqList.cpp
#include <malloc.h>
#include <stdlib.h>
#include <stdio.h>
#include "SqList.h"
Status InitList(SqList &L)
{
L.elem=(ElemType *)malloc(LIST_INIT_SIZE * sizeof(ElemType));
if(!L.elem)
exit(ERROR);
L.length=0;
L.listsize=LIST_INIT_SIZE;
return OK;
}
Status DestoryList(SqList &L)
{
free(L.elem);
return OK;
}
Status ClearList(SqList &L)
{
L.length=0;
return OK;
}
Status GetElem(SqList L,int i,int &e)
{
e=L.elem[i-1];
return OK;
}
Status ListInsert(SqList &L,int i,int e)
{
if(i>L.length+1 || i<1)
return ERROR;
if(L.length>=L.listsize)
{
ElemType *newbase=(ElemType *) realloc(L.elem,(L.listsize+LIST_INCREMENT)* sizeof(ElemType));
if(!newbase)
return ERROR;
L.elem=newbase;
L.listsize+=LIST_INCREMENT;
}
ElemType *q=&(L.elem[i-1]);//q为插入位置
ElemType *p;
for(p=&(L.elem[L.length-1]);p>=q;p--)
*(p+1)=*p;
*q=e;
L.length++;
return OK;
}
Status ListDelete(SqList &L,int i,int &e)
{
if(i<1 || i>L.length+1)
return ERROR;
e=L.elem[i-1];
ElemType *p=&(L.elem[i-1]);//删除的元素位置
ElemType *q;
for(q=p;q<=&(L.elem[L.length-1]);q++)
*q=*(q+1);
L.length-=1;
return OK;
}
Status LocateElem(SqList L,int e)
{
for(int i=0;i<L.length;i++)
{
if(L.elem[i]==e)
{
return OK;
break;
}
}
return ERROR;
}
Status ErgodicList(SqList L)
{
for(int i=0;i<L.length;i++)
{
printf("第%d个:%d\n",i+1,L.elem[i]);
}
printf("线性表长度:%d\n",L.length);
printf("线性表大小:%d\n",L.listsize);
return OK;
}
3.主函数main.cpp
#include <stdio.h>
#include "SqList.h"
int main()
{
SqList L;
ElemType e;
int flag;
InitList(L);//初始化
//赋值
for(int i=1;i<12;i++)
{
ListInsert(L,i,i);//插入
}
GetElem(L,4,e);//获取第四个元素
ErgodicList(L);//遍历
printf("%d\n",e);//打印
flag=LocateElem(L,e);//查找是否存在e
printf("%d\n",flag);//查看返回结果
ListDelete(L,6,e);//删除
ErgodicList(L);//遍历
printf("%d\n",e);//打印
DestoryList(L);//销毁
return 0;
}