单链表
直接看实现吧:
1 #include <cstdio> 2 #include <cstdlib> 3 4 typedef int itemType; 5 struct Node; 6 typedef struct Node *pNode; 7 typedef pNode list; 8 typedef pNode position; 9 10 struct Node { 11 itemType item; 12 position next; 13 }; 14 15 list 16 MakeEmpty(list l) 17 { 18 l->item = 0; 19 l->next = NULL; 20 } 21 22 int 23 IsEmpty(list l) 24 { 25 /* 26 if (l->next == NULL) { 27 return 1; 28 } else { 29 return 0; 30 } 31 */ 32 return l->next == NULL; 33 } 34 35 int 36 IsLast(position p, list l) 37 { 38 return p->next == NULL; 39 } 40 41 position 42 Find(itemType item, list l) 43 { 44 position p; 45 46 p = l->next; 47 while (p != NULL && p->item != item) { 48 p = p->next; 49 } 50 51 return p; 52 } 53 54 position 55 FindPrevious(itemType item, list l) 56 { 57 position p; 58 59 p = l; 60 while (p->next != NULL && p->next->item != item) { 61 p = p->next; 62 } 63 64 return p; 65 } 66 67 void 68 Delete(itemType item, list l) 69 { 70 position p, tmp; 71 72 p = FindPrevious(item, l); 73 74 if (!IsLast(p, l)) { 75 tmp = p->next; 76 p->next = tmp->next; 77 free(tmp); 78 } 79 } 80 81 void 82 Insert(itemType item, list l, position p) 83 { 84 position tmp; 85 86 tmp = (position)malloc(sizeof(struct Node)); 87 if (tmp == NULL) { 88 printf("Out of space!\n"); 89 return; 90 } 91 92 tmp->item = item; 93 tmp->next = p->next; 94 p->next = tmp; 95 } 96 97 void 98 DeleteList(list l) 99 { 100 position p, tmp; 101 102 p = l->next; 103 while (p != NULL) { 104 tmp = p; 105 p = p->next; 106 free(tmp); 107 } 108 free(l); 109 } 110 111 position 112 Header(list l) 113 { 114 return l; 115 } 116 117 position 118 First(list l) 119 { 120 return l->next; 121 } 122 123 position 124 Advance( position p ) 125 { 126 return p->next; 127 } 128 129 itemType 130 Retrieve( position p ) 131 { 132 return p->item; 133 } 134 135 void 136 PrintList( list l) 137 { 138 position p; 139 p = First(l); 140 while (p != NULL) { 141 printf("%d\t", Retrieve(p)); 142 p = Advance(p); 143 } 144 printf("\n"); 145 } 146 147 int 148 main(int argc, char** argv) 149 { 150 list l; 151 // init 152 l = (list)malloc(sizeof(struct Node)); 153 MakeEmpty(l); 154 // insert some elememts 155 position p; 156 p = Header(l); 157 for (int i = 0; i < 10; i++) { 158 Insert(i, l, p); 159 p = Advance(p); 160 } 161 // retrieve 162 PrintList(l); 163 // find and delete 164 Delete(0, l); 165 Delete(9, l); 166 Delete(100, l); 167 PrintList(l); 168 169 system("pause"); 170 return 0; 171 }