这里给出【数据结构(C语言)第二版慕课版 人民邮电出版社】中P20~23中HeaderList的例程
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
|
#include <stdio.h> #include <malloc.h> typedef int ElemType; typedef struct node { ElemType element; struct node *link; }Node; typedef struct headerList { Node *head; int n; }HeaderList;
void Init(HeaderList *h);
ElemType Find(HeaderList *h, int i);
void Insert(HeaderList *h, int i,ElemType x);
void Delete(HeaderList *h, int i); void Output(HeaderList *h); void Destory(HeaderList *h); int main() { int i; int x; HeaderList list; Init(&list); for(i=0; i<9; i++) Insert(&list, i-1, i); Output(&list); Delete(&list, 0); Output(&list); x = Find(&list, 5); printf("%d\n", x); Destory(&list); return 0; } void Init(HeaderList *h) { h->head = (Node*)malloc(sizeof(Node)); h->head->link = NULL; h->n = 0; } void Insert(HeaderList *h, int i,ElemType x) { Node *p, *q; int j; if(i<-1 || i>h->n-1) return; p = h->head; for(j=0; j<=i; j++) p = p->link; q = (Node *)malloc(sizeof(Node)); q->element = x; q->link = p->link; p->link = q; h->n++; }
ElemType Find(HeaderList *h, int i) { Node *p; int j; if(i<0 || i>h->n-1) return NULL; p = h->head; for(j=0; j<=i; j++) p = p->link; return p->element; }
void Delete(HeaderList *h, int i) { int j; Node *p, *q; if(!h->n) return; if(i<-1 || i>h->n-1) return; q = h->head; for(j=0; j<i; j++) q = q->link; p = q->link; q->link = p->link; free(p); h->n--; } void Output(HeaderList *h) { Node *p; if(!h->head) return; p = h->head->link; while(p) { printf("%d ", p->element); p = p->link; } printf("\n"); } void Destory(HeaderList *h) { Node *p; while(h->head) { p = h->head->link; free(h->head); h->head = p; } }
|