//线性表函数操作
#include
#include
#define MaxSize 30
#define Error 0
#define True 1
typedef char ElemType;
typedef struct
{
ElemType elem[MaxSize];
int length;
}SqList; /*顺序表类型定义*/
void InitList(SqList * &L) /*初始化顺序表L*/
{
L = (SqList *)malloc(sizeof(SqList));
L -> length = 0;
}
void DestroyList( SqList *L ) /*释放顺序表L*/
{
free(L);
}
int ListEmpty( SqList *L ) /*判断顺序表L是否为空表*/
{
return( L -> length == 0);
}
int ListLength( SqList *L ) /*返回顺序表L的元素个数*/
{
return( L -> length);
}
void DispList( SqList *L ) /*输出顺序表L*/
{
int i;
if( ListEmpty(L))
return;
for( i = 0; i < L -> length; i++ )
printf("%c", L -> elem[i]);
printf("\n");
}
int GetElem( SqList *L, int i, ElemType &e) /*获取顺序表中的第i个元素*/
{
if( i < 1 || i > L -> elem[i])
return Error;
e = L -> elem[i - 1];
return True;
}
int LocateElem( SqList *L, ElemType e) /*在顺序表中查找元素e*/
{
int i = 0;
while( i < L -> length && L -> elem[i] != e)
i++;
if(i >= L -> length)
return Error;
else
return i+1;
}
int ListInsert( SqList * &L, int i, ElemType e) /*在顺序表L中第i个位置插入元素e*/
{
int j;
if( i < 1 || i > L -> length + 1)
return 0;
i--; /*将顺序表位序转化为elem下标*/
for( j = L -> length; j > i; j--) /*将elem[i]及后面元素后移一个位置*/
L -> elem[j] = L -> elem[j - 1];
L -> elem[i] = e;
L -> length++; /*顺序表长度增1*/
return True;
}
int ListDelete( SqList * &L, int i, ElemType &e) /*顺序表L中删除第i个元素*/
{
int j;
if( i < 1 || i > L -> length)
return Error;
i--; /*将顺序表位序转化为elem下标*/
e = L -> elem[i];
for(j = i; j < L -> length - i; j++)
L -> elem[j] = L -> elem[j + 1];
L -> length--; /*顺序表长度减1*/
return True;
}
void main()
{
SqList *L;
ElemType e;
printf("(1)初始化顺序表L\n");
InitList(L);
printf("(2)依次采用尾插法插入a,b,c,d,e元素\n");
ListInsert(L, 1, 'a');
ListInsert(L, 2, 'b');
ListInsert(L, 3, 'c');
ListInsert(L, 4, 'd');
ListInsert(L, 5, 'e');
printf("(3)输出顺序表L:");
DispList(L);
printf("(4)顺序表L长度 = %d\n", ListLength(L));
printf("(5)顺序表L为%s\n", (ListEmpty(L) ?"空" :"非空"));
GetElem(L, 3, e);
printf("(6)顺序表L的第3个元素 = %c\n", e);
printf("(7)元素a的位置 = %d\n", LocateElem(L,'a'));
printf("(8)在第4个元素位置上插入f元素\n");
ListInsert(L, 4, 'f');
printf("(9)输出新的顺序表L:");
DispList(L);
printf("(10)删除L的第3个元素\n");
ListDelete(L, 3, e);
printf("(11)输出新的顺序表L:");
DispList(L);
printf("(12)释放顺序表L\n");
DestroyList(L);
}