2018-04-12
how to write list in c
List.h
#ifndef _List_H
#define _List_H
struct Node;
typedef struct Node *PtrToNode;
typedef PtrToNode List;
typedef PtrToNode Position;
List MakeEmpty(List L);
int IsEmpty(List L);
int IsLast(Position P,List L);
Position Find(ElementType X,List L);
void Delete(ElementType X,List L);
Position FindPrevious(ElementType X,List L);
void Insert(ElementType X,List L,Position P);
void DeleteList(List L);
Position Header(List L);
Position First(List L);
Position Advance(Position P);
ElementType Retrieve(Position P);
#endif /*_List_H */
List.c
#include "List.h"
#include <stdlib.h>
#include "fatal.h"
struct Node
{
ElementType Element;
Position Next;
};
List MakeEmpty(List L){
if(L !=NULL)
DeleteList(L);
L=malloc(sizeof(struct Node));
if(L==NULL)
FatalError("Out of memory!");
L->Next = NULL;
return L;
}
int IsEmpty(List L){
return L->Next == NULL;
}
int IsLast(Position P,List L){
return P->Next==NULL;
}
Position Find(ElementType X,List L){
Position P;
P=L->Next;
while(P!=NULL && P->Element != X)
P=P->Next;
return P;
}
void Delete(ElementType X,List L){
Position P,TmpCell;
P = FindPrevious(X,L);
if(!IsLast(P,L)){
TmpCell = P->Next;
P->Next = TmpCell->Next;
free(TmpCell);
}
}
Position FindPrevious(ElementTpye X,List L){
Position P;
P=L;
while(P->Next !=NULL && P->Next->Element != X)
P= P->Next;
return P;
}
void Insert(ElementType X,List L,Position P){
Position TmpCell;
TmpCell = malloc(sizeof(struct Node));
if(TmpCell == NULL)
FatalError("Out of space!!!");
TmpCell->Element = X;
TmpCell->Next = P->Next;
P->Next = TmpCell;
}
if 0
void DeleteList(List L)
{
Position P;
P = L->Next;
L->Next=NULL;
while(P!=NULL)
{
free(P);
P= P->Next;
}
}
endif
void DeleteLIst(List L)
{
Position P,Tmp;
P=L->Next;
L-Next =NULL;
while(P!=NULL){
Tmp = P->Next;
free(P);
P=Tmp;
}
}
Position Header(List L){
return L;
}
Position First(List L){
return L->Next;
}
Position Advance(Position P){
return P->Next;
}
ElementType Retrieve(Position P)
{
return P->Element;
}
fatal.h
#include<stdio.h>
#include<stdlib.h>
#define Error(Str) FatalError(Str)
#define FatalError(Str) fprintf(stderr,"%s\n",Str),exit(1)
网友评论