- 头文件
#define LIST_INIT_SIZE 100
#define LISTINCREMENT 10
#define TRUE 1
#define FALSE 0
#define OK 1
#define ERROR 0
#define INFEASIBLE -1
#define OVERFLOW -2
#include <stdlib.h>
#include <stdio.h>
#define TRUE 1
#define FALSE 0
#define OK 1
#define ERROR 0
#define INFEASIBLE -1
#define OVERFLOW -2
typedef int Status;
typedef int ElemType;
typedef struct {
ElemType* elem;
int lenth;
int listsize;
}SqList;
Status InitList(SqList&);
Status ListInsert(SqList&, int, ElemType);
Status GetElem(SqList, int, ElemType&);
int ListLength(SqList);
Status ListTraverse(SqList&, void (*)(ElemType));
Status ListMerge(SqList, SqList,SqList& );
void out(ElemType);
Status DetroyList(SqList&);
Status ClearList(SqList& );
Status ListDelete(SqList&, int, ElemType&);
Status ListEmpty(SqList );
- 函数文件
#include "List.h"
void out(ElemType e) {
printf("%d ", e);
}
Status InitList(SqList& L) {
L.elem = (ElemType*)malloc(LIST_INIT_SIZE * sizeof(ElemType));
if (!L.elem) exit(OVERFLOW);
L.lenth = 0;
L.listsize = LIST_INIT_SIZE;
return OK;
}
Status DetroyList(SqList& L) {
if (!L.elem) return ERROR;
free(L.elem);
L.elem = NULL;
L.lenth = 0;
L.listsize = 0;
return OK;
}
Status ClearList(SqList& L) {
if (!L.elem) return ERROR;
L.elem = NULL;
return OK;
}
Status GetElem(SqList L, int i, ElemType& e) {
if ((i < 1) || (i > L.lenth)) return ERROR;
e = L.elem[i - 1];
return OK;
}
int ListLength(SqList L){
return L.lenth;
}
Status ListDelete(SqList& L, int i, ElemType& e) {
if (i<1 || i>L.lenth) return ERROR;
e = L.elem[i - 1];
int j;
for (j = i;j <= L.lenth - 1;++j) {
L.elem[j - 1] = L.elem[j];
}
--L.lenth;
return OK;
}
Status ListEmpty(SqList L) {
if (!L.elem) return TRUE;
else return ERROR;
}
Status ListTraverse(SqList& L, void (*visit)(ElemType))
{
int i, L_len = ListLength(L);
ElemType e;
for (i = 1; i <= L_len; i++) {
GetElem(L, i, e);
(*visit)(e);
}
return OK;
}
int equal(ElemType x, ElemType y){
return x == y;
}
Status ListInsert(SqList& L, int i, ElemType e) {
if (i<1 || i>L.lenth + 1) return ERROR;
ElemType* p, * q;
if (L.lenth >= L.listsize) {
ElemType* newbase;
newbase = (ElemType*)realloc(L.elem, (L.listsize + LISTINCREMENT) * sizeof(ElemType));
if (!newbase) exit(OVERFLOW);
L.elem = newbase;
L.listsize += LISTINCREMENT;
}
q = &(L.elem[i - 1]);
for (p = &(L.elem[L.lenth - 1]); p >= q;--p) {
*(q + 1) = *p;
}
*q = e;
++L.lenth;
return OK;
}