#include <stdio.h>
#include <stdlib.h>
#define INIT_SIZE 10
#define ERROR -1
#define OK 1
typedef int ElemType;
typedef bool Status;
typedef Status (*CALL_FN)(ElemType);
typedef struct list
{
ElemType* elem;
ElemType size;
ElemType length;
}List;
void InitList(List* L)
{
L->elem = (ElemType*)malloc(INIT_SIZE*sizeof(ElemType));
if (!L->elem)
printf("failed to initialize the list");
L->size = INIT_SIZE;
L->length = 0;
}
ElemType getListLength(List L)
{
return L.length;
}
Status ListEmpty(List L)
{
if(L.length == 0)
return true;
else
return false;
}
Status ClearList(List *L)
{
free(L->elem);
}
Status getItem(List L, int i, ElemType* e)
{
if(i <0 || i>L.length-1)
return ERROR;
if(ListEmpty(L))
return ERROR;
*e = L.elem[i];
return OK;
}
Status InsertList(List *L, int i, ElemType e)
{
L->elem = (ElemType*)realloc(L->elem, (L->length+1)*sizeof(ElemType));
if (!L->elem)
return ERROR;
for(int j = i; j<=L->length-1; j++)
{
*(L+j+1) = *(L+j);
}
(*L).elem[i] = e;
//*(L+i) = e;
L->size = L->size +1;
L->length = L->length +1;
return OK;
}
Status DeleteList(List* L, int i, ElemType* e)
{
for(int j = i; j<=L->length-2; j++)
*(L+j) = *(L+j+1);
L->length = L->length-1;
return OK;
}
Status TraverseList(List L, CALL_FN visit)
{
for(int i =0; i<=L.length-1; i++)
visit(i);
return OK;
}
Status display(List L)
{
for (int i =0; i<=L.length-1; i++)
printf("%d ", L.elem[i]);
printf("\n");
}
Status visit(ElemType i)
{
printf("%d visited.\n", i);
}
int main()
{
List A;
List * p;
p = &A;
InitList(p);
display(A);
InsertList(p, 0, 1);
InsertList(p, 1, 2);
InsertList(p, 2, 3);
InsertList(p, 3,4);
display(A);
int e;
int* p_e = &e;
getItem(A, 2, p_e);
printf("p_e is:%d\n", *p_e);
TraverseList(A, visit);
}
线性表-顺序存储结构的C语言实现
最新推荐文章于 2020-12-26 13:38:59 发布