程序如下#include <stdio.h>
#include <malloc.h>
#define MaxSize 50
typedef int ElemType;
typedef struct
{
ElemType data[MaxSize];
int length;
} SqList;
void InitList(SqList *&L);
void ListInsert(SqList *L,int i,int b);
void DispList(SqList *L);
bool ListEmpty(SqList *L);
void DestroyList(SqList *L);
int ListDelete(SqList *, int , int &);
bool ListEmpty(SqList *L);
int ListLength(SqList *L);
int LocateElem(SqList *l, ElemType e);
bool GetElem(SqList *l,int i,ElemType &e);
int main()
{
SqList *sq;
int e,a,loc;
int i=2;
InitList(sq);
ListInsert(sq, 1, 5);
ListInsert(sq, 2, 3);
ListInsert(sq, 1, 4);
DispList(sq);
printf("线性表的长度:%d\n",ListLength(sq));
if(GetElem(sq, 3, a))
printf("找到了第3个元素值为:%d\n", a);
else
printf("第3个元素超出范围!\n");
if((loc=LocateElem(sq, 8))>0)
printf("找到了,值为8的元素是第 %d 个\n", loc);
else
printf("值为8的元素木有找到!\n");
ListDelete(sq,i,e);
printf("删除的元素是:%d\n",e);
printf("删除后的线性表:");
DispList(sq);
DestroyList(sq);
return 0;
}
void DispList(SqList *L)
{
int i;
if (ListEmpty(L))
return;
for (i=0; i<L->length; i++)
printf("%d ",L->data[i]);
printf("\n");
}
bool ListEmpty(SqList *L)
{
return(L->length==0);
}
void InitList(SqList *&L)
{
L=(SqList *)malloc(sizeof(SqList));
L->length=0;
}
void ListInsert(SqList *L,int i,int b)
{
int j;
if(i<1)
{
printf("插入位置非法/n");
}
i=i-1;
if(L->length==0)
{
L->data[i]=b;
L->length++;
}
else
{
for(j=L->length;j>i;j--)
{
L->data[j]=L->data[j-1];
}
L->data[i]=b;
L->length++;
}
}
void DestroyList(SqList *L)
{
free(L);
printf("线性表已经被释放!线性表的长度:%d",L->length);
printf("\n(由于线性表已经被释放所以显示的长度为随机值)");
}
int ListDelete(SqList *L, int i, int &e)
{
i--;
int n=0;
while(n<i)
n++;
if(L->length>n)
{
e=L->data[n];
while(n<L->length-1)
{
L->data[n]=L->data[n+1];
n++;
}
L->length--;
}
return e;
}
int ListLength(SqList *L)
{
return L->length;
}
bool GetElem(SqList *l,int i,ElemType &e)
{
if(i<1||i>l->length)
return false;
e=l->data[i-1];
return true;
}
int LocateElem(SqList *l, ElemType e)
{
int i=0;
while(l->length>i&&l->data[i]!=e)
{
i++;
}
if(i>=l->length)
{
return 0;
}
return i+1;
}
运行结果如下