顺序表的基本运算如下:
(1)初始化顺序表L
(2)依次插入a,b,c,d,e元素
(3)输出顺序表L:a b c d e
(4)顺序表L长度:5
(5)顺序表L为非空
(6)顺序表L的第3个元素:c
(7)元素a的位置:1
(8)在第4个元素位置上插入f元素
(9)输出顺序表L:a b c f d e
(10)删除L的第3个元素
(11)输出顺序表L:a b f d e
(12)释放顺序表L
#include <stdio.h>
#include <stdlib.h>
#define OK 1
#define ERROR 0
#define LIST_INIT_SIZE 100
#define LISTINCREMENT 10
typedef char ElemType;
typedef int Status;
typedef struct
{
ElemType *elem;
int length;
int listsize;
} SqList;
// 算法2.3 初始化
Status InitList_Sq(SqList &L)
{
L.elem = (ElemType *)malloc(LIST_INIT_SIZE*sizeof(ElemType));
if (!L.elem) exit(-1); // 存储分配失败
L.length = 0;
L.listsize = LIST_INIT_SIZE;
return OK;
}
// 算法2.4 插入
Status ListInsert_Sq(SqList &L, int i, ElemType e)
{
ElemType *p, *q;
if (i < 1 || i > L.length+1)
{// i的合法值为1≤i≤ListLength_Sq(L)+1
return ERROR;
}
if (L.length >= L.listsize) {// 当前存储空间已满,增加容量
ElemType *newbase = (ElemType *)realloc(L.elem,
(L.listsize+LISTINCREMENT)*sizeof (ElemType));
if (!newbase) return ERROR;
L.elem = newbase;
L.listsize += LISTINCREMENT;
}
q = &(L.elem[i-1]);
for (p = &(L.elem[L.length-1]); p>=q; --p)
*(p+1) = *p;
*q = e;
++L.length;
return OK;
}
//算法2.5 删除
Status ListDelete_Sq(SqList &L,int i, ElemType &e)
{
ElemType *p,*q;
if(i<1||i>L.length) return ERROR;
p=L.elem+i-1; //p=&(L.elem[i-1]);
e=*p;
q=L.elem+L.length-1;//最后一个元素的位置
for(++p;p<=q;p++)
*(p-1)=*p;
--L.length;
}
//销毁顺序表操作
Status DestroyList(SqList &L)
{
free(L.elem);
L.elem=NULL;
L.length=0;
L.listsize=0;
return OK;
}
Status ListEmpty(SqList L)
{
if(L.length==0)
return 1;
else
return 0;
}
int main()
{
char A[5] = {'a','b','c','d','e'},temp='f';
//temp用来存放插入的字符以及保存删除字符的值
int i;
SqList List;
InitList_Sq(List);
for(i=1; i<=5; i++)
ListInsert_Sq(List,i,A[i-1]);
if(!ListEmpty(List))
printf("顺序表非空
");
printf("开始时元素序列为:
");
for(i=1; i<= List.length; i++)
printf("%c ", List.elem[i-1]);
i=4; //插入位置
ListInsert_Sq(List,i,temp);
printf("
插入后的元素序列为:
");
for(i=1; i<= List.length; i++)
printf("%c ", List.elem[i-1]);
i=3;
ListDelete_Sq(List,i,temp) ;
printf("
删除后的元素序列为:
");
for(i=1; i<= List.length; i++)
printf("%c ", List.elem[i-1]);
if(DestroyList(List))
printf("
成功释放顺序表L");
getchar();
}