#include "../include.h"
#define LIST_INIT_SIZE 3
#define LISTINCREMENT 2
typedef struct
...{
ElemType *base;
int length;
int listsize;
}List;
Status InitList(List *l)
...{
l->base = (ElemType *)malloc(LIST_INIT_SIZE * sizeof(ElemType));
if(!l->base)
...{
exit(OVERFLOW);
}
l->length = 0;
l->listsize = LIST_INIT_SIZE;
}
Status DestoryList(List *l)
...{
if(!l->base)
...{
free(l->base);
}
l->length = 0;
l->listsize = 0;
}
Status ListInsert(List *l,ElemType e,int i)
...{
if(i < 0 || i > l->length)
...{
return ERROR;
}
if(l->length >= l->listsize)
...{
ElemType *newbase = (ElemType *)realloc(l->base,(l->listsize + LISTINCREMENT) * sizeof(ElemType));
if(!newbase)
...{
exit(OVERFLOW);
}
l->base = newbase;
l->listsize += LISTINCREMENT;
}
ElemType *pei = l->base + i;
ElemType *pej = l->base + l->length - 1;
while(pej >= pei)
...{
*(pej + 1) = *pej;
pej--;
}
*pei = e;
l->length++;
return OK;
}
Status ListDelete(List *l,ElemType *e,int i)
...{
if(i < 0 || i >= l->length)
...{
return ERROR;
}
ElemType *pei = l->base + i;
ElemType *pej = l->base + l->length - 1;
*e = *pei;
while(pei < pej)
...{
*pei = *(pei + 1);
pei++;
}
l->length--;
return OK;
}
int Locate(List l,ElemType e)
...{
int i;
for(i = 0; i < l.length; i++)
...{
if(*(l.base + i) == e)
...{
return i;
}
}
return INFEASIBLE;
}
void Print(List l)
...{
int i;
for(i = 0; i < l.length; i++)
...{
printf("%d ",*(l.base + i));
}
printf(" ");
}
int main()
...{
List l;
printf("Init list...");
InitList(&l);
printf("initialed. ");
printf("Insert elements: 6 3 2 19 0 9 38 42 85 99 34 63 ");
ListInsert(&l,6,0);
ListInsert(&l,3,1);
ListInsert(&l,2,2);
ListInsert(&l,19,3);
ListInsert(&l,63,4);
ListInsert(&l,34,4);
ListInsert(&l,99,4);
ListInsert(&l,85,4);
ListInsert(&l,42,4);
ListInsert(&l,38,4);
ListInsert(&l,9,4);
ListInsert(&l,0,4);
printf("Result: ");
Print(l);
printf("Locate elements: 42 63 6 ");
printf("Result: ");
printf("%d ",Locate(l,42));
printf("%d ",Locate(l,63));
printf("%d ",Locate(l,6));
printf("Delete elements: 0 42 63 6 ");
ElemType e;
ListDelete(&l,&e,11);
ListDelete(&l,&e,7);
ListDelete(&l,&e,4);
ListDelete(&l,&e,0);
printf("Result: ");
Print(l);
printf("Destory list...");
DestoryList(&l);
printf("destoried. ");
}
本文介绍了一种使用动态数组的数据结构实现方法,并提供了关键函数的代码示例,包括初始化、插入、删除等操作。
2154





