单向链表的实现,头文件。 #ifndef _List_H #define _List_H struct Node; typedef struct Node *PtrToNode; typedef PtrToNode List; typedef PtrToNode Position; List InitList(); int 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); List Revert(List L); #endif C文件 #include <stdio.h> #include <stdlib.h> #include <assert.h> #include "List.h" struct Node { int Element; Position Next; }; List InitList() { List temp; temp = (List)malloc(sizeof(struct Node)); temp->Next = NULL; return temp; } int IsEmpty(List L) { assert(L!=NULL); return L->Next == NULL; } int IsLast(Position P,List L) { assert(L!=NULL); return P->Next == NULL; } List Revert(List L) { Position Head, pos1, pos2, pos3; assert(L!=NULL); Head = L; if ( Head->Next == NULL ) return Head; pos1 = Head, pos2 = pos1->Next; while( pos2 != NULL ) { pos3 = pos2->Next; pos2->Next = pos1; pos1 = pos2; if ( pos1 == Head->Next) pos1->Next = NULL; pos2 = pos3; } Head->Next = pos1; return Head; } Position Find(int X, List L) { Position P; assert(L!=NULL); P = L->Next; while( P!=NULL && P->Element != X ) P = P->Next; return P; } Position FindPrevious(int X, List L) { Position P; assert(L!=NULL); P = L; while( P->Next != NULL && P->Next->Element != X ) P = P->Next; return P; } void Delete(int X, List L) { Position P, TmpCell; assert(L!=NULL); P = FindPrevious(X, L); if ( !IsLast(P,L) ) { TmpCell = P->Next; P->Next = TmpCell->Next; free(TmpCell); } else { TmpCell = P->Next; P->Next = TmpCell->Next; free(TmpCell); } } void Insert(int X, List L, Position P) { Position TmpCell; TmpCell = malloc(sizeof(struct Node)); assert(TmpCell!=NULL); TmpCell->Element = X; TmpCell->Next = P->Next; P->Next = TmpCell; } void DeleteList(List L) { Position P, Tmp; P = L->Next; L->Next = NULL; while(P!=NULL) { Tmp = P->Next; free(P); P = Tmp; } } void PrintList(List L) { Position P; assert(L!=NULL); P = L->Next; while(P!=NULL) { printf("---%d---/n", P->Element); P = P->Next; } } int main(int argc, char **argv) { Position pos; List demo = InitList(); Insert(2, demo, demo); Insert(5, demo, demo); PrintList(demo); Delete(2, demo); pos = Find(5, demo); if ( pos!=NULL ) printf("%d/n", pos->Element); PrintList(demo); DeleteList(demo); PrintList(demo); Insert(1, demo, demo); Insert(2, demo, demo); Insert(3, demo, demo); Insert(4, demo, demo); PrintList(demo); pos = Revert(demo); PrintList(pos); return 0; }