List.h
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#ifndef _LIST_H
struct Node;
typedef struct Node *PtrToNode;
typedef PtrToNode List;
typedef PtrToNode Position;
struct Node {
int Element;
Position Next;
};
List MakeEmpty(List L);
bool IsEmpty(List L);
bool IsLast(Position p, List L);
Position Find(int x, List L);
void Delete(int x, List L);
Position FindPrevious(int x, List L);
void Insert(int x, List L, Position p);
void DeleteList(List L);
Position Header(List L);
Position First(List L);
Position Advance(Position p);
int Retrieve (Position p);
#endif
List.c
#include "List.h"
List MakeEmpty(List L) {
L = malloc(sizeof(struct Node));
return L;
}
bool IsEmpty(List L) {
return L->Next == NULL;
}
bool IsLast(Position p, List L) {
return p->Next == NULL;
}
Position Find(int x, List L) {
Position p;
p = L->Next;
while (p != NULL && p->Element != x) {
p = p->Next;
}
return p;
}
void Delete(int x, List L) {
Position p, temppos;
p = FindPrevious(x,L);
if (!IsEmpty(L)) {
temppos = p->Next;
p->Next = temppos->Next;
free(temppos);
}
return;
}
Position FindPrevious(int x, List L) {
Position p;
p = L;
while (p != NULL && p->Next->Element != x) {
p = p->Next;
}
return p;
}
void Insert(int x, List L, Position p) {
PtrToNode tempNode = malloc(sizeof(struct Node));
if (!tempNode) {
printf("Out of memory\n");
}
tempNode->Element = x;
tempNode->Next = p->Next;
p->Next = tempNode;
return;
}
void DeleteList(List L) {
if (!L->Next) {
Position p = L->Next;
while (p) {
Position temp = p->Next;
free(p);
p = temp;
}
}
return;
}
Position Header(List L) {
return L;
}
Position First(List L) {
if (!L) {
return L->Next;
}
return NULL;
}
Position Advance(Position p) {
if (!p->Next) {
return p->Next;
}
return NULL;
}
int Retrieve (Position p) {
if (!p) {
return p->Element;
}
printf("Empty Node\n");
return 0;
}
main.c
#include "List.h"
#define MAXNODENUMBER 10
void print(List L) {
Position p;
p = L->Next;
while (p) {
printf("Current Node Value: %d\n", p->Element);
p = p->Next;
}
return;
}
int main(int argc, char **argv) {
PtrToNode arr[MAXNODENUMBER];
for (int i = 0; i < MAXNODENUMBER; ++i) {
arr[i] = malloc(sizeof(struct Node));
arr[i]->Element = i;
}
List L;
L->Next = arr[0];
int j;
for (j = 0; j < MAXNODENUMBER -1; ++j) {
arr[j]->Next = arr[j+1];
}
arr[j]->Next = NULL;
arr[j]->Element = MAXNODENUMBER -1;
print(L);
DeleteList(L);
return 0;
}
编译命令:
gcc -g -Wall -std=c99 main.c List.c -o main