线性表的顺序存储结构代码
#define MAXSIZE 20 /*存储空间初始分配量*/
typedef int ElemType; /*ElemType类型根据实际情况而定,这里假设为int*/
typedef struct
{
ElemType data[MAXSIZE ]; /*数组存储数据元素,最大值为MAXSIZE*/
int length; /*线性表当前长度*/
}SqList;
List.h /*头文件*/
#define MAXSIZE 20
#define OK 1
#define ERROR 0
typedef int Status;
typedef int ElemType;
typedef struct
{
ElemType data[MAXSIZE];
int length;
}SqList;
Status CreateList(SqList *L); /*创建线性表*/
Status GetElem(SqList *L, int i, ElemType *e); /*根据所在位置得到该位置的元素值*/
Status ListInsert(SqList *L, int i, ElemType e); /*插入元素值*/
Status ListDelete(SqList *L, int i, ElemType *e); /*删除元素值*/
void PrintList(SqList *L); /*打印线性表*/
List.c /*源文件*/
Status CreateList(SqList *L)
{
int i;
printf("输入线性表的长度:\n");
scanf("%d", &(L->length));
if(L->length<0 || L->length>MAXSIZE)
{
return ERROR;
}
for(i=0; i
{
L->data[i] = i+1;
}
return OK;
}
Status GetElem(SqList *L, int i, ElemType *e)
{
if(i<1 || i>L->length || L->length==0)
{
return ERROR;
}
*e = L->data[i-1];
return OK;
}
Status ListInsert(SqList *L, int i, ElemType e)
{
int j = 0;
if(L->length == MAXSIZE)
{
return ERROR;
}
if(i<1 || i>L->length+1)
{
return ERROR;
}
for(j=L->length; j>=i; j--)
{
L->data[j] = L->data[j-1];
//printf("%d\n", L->data[j]);
}
//printf("\n");
L->data[i-1] = e;
L->length++;
return OK;
}
Status ListDelete(SqList *L, int i, ElemType *e)
{
int j = 0;
if(L->length == 0)
{
return ERROR;
}
if(i<1 || i >L->length)
{
return ERROR;
}
*e = L->data[i-1];
for(j=i; j
{
L->data[j-1] = L->data[j];
}
L->length--;
return OK;
}
void PrintList(SqList *L)
{
int i;
for(i=0; i
{
printf("%d ", L->data[i]);
}
printf("\n");
}