代码:
#include<stdlib.h>
#include<stdio.h>
#define MaxSize 100
typedef int Status,ElemType;
typedef struct SqList{//数组实现
int data[MaxSize];
int length;
}Sqlist;
Status InitList(Sqlist *&L) {//顺序表初始化
L = (Sqlist*)malloc(sizeof(SqList));
if (!L)exit(1);
L->length = 0;
return 0;
}
Status DestroyList(Sqlist *&L) {
free(L);
L = NULL;
}
Status ClearList(SqList *&L) {//清空线性表
if (!L->length) { printf("线性表为空");}
if (L->length) {
for (int i = L->length; i>0;i--) {
L->data[i-1] =L->data[i];
L->length--;
}
}
}
Status ShowList(Sqlist *&L) {//遍历线性表
if (L->length) {
for (int i = 0; i< L->length;i++) {
printf("%d", L->data[i]);
}
}
else {
printf("线性表为空!");
return 1;
}
return 0;
}
Status ListLength(Sqlist *&L) {//返回元素个数
return L->length;
}
Status GetElem(Sqlist *&L,int i,ElemType &e) {//用e返回第i个元素的值
if (i<1 || i>L->length) {
printf("输入的位置i非法");
}
else {
e = L->data[i - 1];
}
return 0;
}
Status LocatElem(Sqlist *&L, ElemType e, int &i) {//返回第一次出现元素e的位置
if (L->length>0) {
while (L->data[i] != e) { i++; }
i++;
return i;
}
else {
printf("该线性表不存在!");
return 1;
}
}
Status NextElem(Sqlist *&L,ElemType cur_e,ElemType &pre_e ) {//返回元素的前趋i1
int i;
LocatElem(L, cur_e, i);
if (1 < i < L->length) {
pre_e = L->data[i-2];
}
else {
printf("操作失败!不存在");
}return 0;
}
Status ListInsert(Sqlist *&L,ElemType e,int i) {//在第i个位置之前插入元素e
if (L->length>0) {
int n =L->length ;
while (n >i) {
L->data[n] = L->data[n-1];
n--;
}
L->data[n] = e;
L->length++;
}
else {
printf("线性表不存在!");
}
}