#include <stdio.h>
#include <malloc.h>
#define MAXSIZE 50
typedef char ElemType;
typedef struct {
ElemType data[MAXSIZE];
int length;
}SqList;
void InitList(SqList * &L) {
L = (SqList *)malloc(sizeof(SqList));
L->length = 0;
printf("初始化成功\n");
}
void DestroyList(SqList *&L) {
free(L);
}
bool ListEmpty(SqList *L) {
return(L->length == 0);
}
int ListLength(SqList *L) {
return(L->length);
}
void DispList(SqList * L) {
int i;
if (ListEmpty(L)) return;
printf("\n当前的线性表为:");
for (i = 0; i < L->length ; i++)
printf("%5c", L->data[i]);
printf("\n");
}
bool GetElem(SqList *L, int i, ElemType &e) {
if (i<0 || i>L->length) return false;
e = L->data[i - 1];
return true;
}
int LocateElem(SqList *L, ElemType e) {
int i = 0;
while (i < L->length && L->data[i] != e) i++;
if (i > L->length) return 0;
else return i + 1;
}
bool ListInsert(SqList *&L, int i, ElemType e) {
int j;
if (i<1 || i>L->length + 1) return false;
i--;
for (j = L->length; j > i; j--)
L->data[j] = L->data[j - 1];
L->data[i] = e;
L->length++;
return true;
printf("插入成功\n");
}
bool ListDelete(SqList *&L, int i, ElemType &e) {
int j;
i--;
if (L->length == 0) return false;
else
e = L->data[i];
for (j = i; j < L->length - 1; j++)
L->data[j] = L->data[j + 1];
L->length--;
return true;
}
int main() {
int x;
ElemType s, t;
SqList * L;
InitList(L);//(1)初始化顺序表L
printf("\n开始插入5个元素:\n", ListLength(L));
ListInsert(L, 1, 'a');
ListInsert(L, 2, 'b');
ListInsert(L, 3, 'c');
ListInsert(L, 4, 'd');
ListInsert(L, 5, 'e');//(2)依次插入a、b、c、d、e元素
DispList(L);//(3)输出顺序表
printf("\n线性表的长度是:%d\n", ListLength(L)); //(4)输出顺序表的长度
if (ListEmpty(L)) printf("\n当前线性表为空\n");
else printf("\n当前线性表不为空\n"); //(5)判断顺序表L是否为空
GetElem(L, 3, s);
printf("\n当前线性表的第3个元素为:%c\n", s); //(6)输出顺序表L的第3个元素
x = LocateElem(L, 'a');
printf("\n元素a的位置是:%d\n", x); //(7)输出元素a的位置
ListInsert(L, 4, 'F');
DispList(L); //(8)在第4个元素位置上插入f元素 //(9)输出顺序表
ListDelete(L, 3, t);
printf("\n删除的第3个元素为:%c\n", t);
DispList(L); //(10)删除顺序表L的第3个元素//(11)输出顺序表
DestroyList(L); //(12)销毁顺序表
}