顺序表
顺序表的各种操作
#include<stdio.h>
#include<malloc.h>
#define MaxSize 50
typedef int ElemType;
typedef struct
{
public:
ElemType data[MaxSize];
int length;
}SqList;
void CreateList(SqList * &L, ElemType a[], int n)
{
int i = 0, k = 0;
L = (SqList*)malloc(sizeof(SqList));
while (i < n)
{
L->data[k] = a[i];
k++;
i++;
}
L->length = k;
} //建立顺序表
void InitList(SqList*& L)
{
L = (SqList*)malloc(sizeof(SqList));
L->length = 0;
} //初始化顺序表
void DestoryList(SqList*& L)
{
free(L);
} //销毁线性表
bool ListEmpty(SqList *L)
{
return(L->length == 0);
} //判断线性表是否为空
int ListLength(SqList* L)
{
return(L->length);
} //求线性表长度
void DispList(SqList* L)
{
for (int i = 0; i < L->length; i++)
printf("%d", L->data[i]);
printf("\n");
} //输出线性表
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 = 1;
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 - i];
L->data[i] = e;
L->length++;
return true;
} //插入数据元素
bool ListDelete(SqList*& L, int i, ElemType e)
{
int j;
if (i<1 || i>L->length)
return false;
i--;
e = L->data[i];
for (j = i; j < L->length - 1; j++)
L->data[i] = L->data[j + 1];
L->length--;
return true;
} //删除元素数据