1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122
| #include <stdio.h> #include <stdlib.h>
struct Node;
typedef int ElementType; typedef struct Node *PtrToNode; typedef PtrToNode List; typedef PtrToNode Position;
struct Node { ElementType Element; Position Next; };
List MakeEmpty(List L); int isEmpty(List L); int IsLast(Position P); 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); void PrintList(List L); Position Header(List L); Position First(List L); Position Advance(Position P); ElementType Retrieve(Position P); void FatalError(const char str[]);
List MakeEmpty(List L) { Position P, Tem; P = L->Next; L->Next = NULL; while (P != NULL) { Tem = P->Next; free(P); P = Tem; } return L; }
int isEmpty(List L) { return L->Next == NULL; }
int IsLast(Position P) { 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, TemCell; P = FindPrevious(X, L); if(!IsLast(P)) { TemCell = P->Next; P->Next = TemCell->Next; free(TemCell); } }
Position FindPrevious(ElementType X, List L) { Position P; P = L; while (P != NULL && P->Next->Element != X) { P = P->Next; } return P; }
void Insert(ElementType X, List L, Position P) { Position TemCell; TemCell = (struct Node *)malloc(sizeof(struct Node)); if (TemCell == NULL) { FatalError("Out of space!!!"); } TemCell->Element = X; TemCell->Next = P->Next; P->Next = TemCell; }
void DeleteList(List L) { Position P, Tem; P = L->Next; free(L); while (P != NULL) { Tem = P->Next; free(P); P = Tem; } }
void PrintList(List L) { Position P; P = L->Next; while (P != NULL) { printf("%d ", P->Element); P = P->Next; } }
void FatalError(const char str[]) { printf("%s", str); }
int main() { List L = (struct Node *)malloc(sizeof(struct Node)); L->Next = NULL; Insert(3, L, L); Insert(2, L, L); Insert(1, L, L->Next); PrintList(L); return 0; }
|