#ifndef _LINKED_LIST_H_#define _LINKED_LIST_H_struct Node;typedefstruct Node *PtrToNode;typedef PtrToNode List;typedef PtrToNode Position;typedefint ElementType;
List initLinkedList(ElementType *X,int NumOfX);
List MakeEmpty(List L);intIsEmpty(List L);intIsLast(Position P, List L);
Position Find(ElementType X, List L);voidDelete(ElementType X, List L);
Position FindPrevious(ElementType X, List L);voidInsert(ElementType X, List L, Position P);voidDeleteList(List L);
Position Header(List L);
Position Advance(Position P);
ElementType Retrieve(Position P);voidPrintList(List L);#endif
链表实现文件 linked_list.c
#include"linked_list.h"#include<stdio.h>#include<stdlib.h>struct Node
{
ElementType Element;
Position Next;};
List initLinkedList(ElementType *X,int NumOfX){int i;
ElementType *Elements = X;
Position Head =NULL;
Position curCell =malloc(sizeof(struct Node));if(curCell ==NULL)printf("Out of space!!!");
Head = curCell;for(i=0; i<NumOfX; i++){
Position tmpCell =malloc(sizeof(struct Node));if(tmpCell ==NULL)printf("Out of space!!!");printf("element:%d line:%d, func:%s\r\n",Elements[i],__LINE__,__FUNCTION__);
tmpCell -> Element = Elements[i];
curCell -> Next = tmpCell;
curCell = tmpCell;}return Head;}intIsEmpty(List L){return L -> Next ==NULL;}intIsLast(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;}voidDelete(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(ElementType X, List L){
Position P;
P = L;while(P -> Next !=NULL&& P -> Next -> Element != X)
P = P -> Next;return P;}voidInsert(ElementType X, List L, Position P){
Position TmpCell;
TmpCell =malloc(sizeof(struct Node));if(TmpCell ==NULL)printf("Out of space!!!");
TmpCell -> Element = X;
TmpCell -> Next = P -> Next;
P -> Next = TmpCell;}voidPrintList(List L){int i =1,j;
List tmpList = L -> Next;while(tmpList -> Next !=NULL){
tmpList = tmpList -> Next;
i++;}
j = i;
tmpList = L -> Next;for(;i>0;i--){printf("List[%d] = %d\r\n",j-i, tmpList -> Element);
tmpList = tmpList -> Next;}}
链表调用主函数 main.c
#include<stdio.h>#include"linked_list.h"enum ListMethod
{
INSERT,
DELETE,
PRINTLIST,};voidprintInfo(void);intmain(){int num,n;
ElementType X[]={1,2,564,4,45,6};
List listHead =initLinkedList(X,sizeof(X)/4);PrintList(listHead);while(1){printInfo();scanf("%d",&num);switch(num){case INSERT:printf("input a number:");scanf("%d",&num);Insert(num, listHead, listHead);break;case DELETE:printf("input a number:");scanf("%d",&num);Delete(num, listHead);break;case PRINTLIST:PrintList(listHead);break;default:printf("input error!!!\r\n");break;}}return0;}voidprintInfo(void){printf("\
ListMethod:\r\n\
Insert -> 0\r\n\
Delete -> 1\r\n\
print list -> 2\r\n\
");}