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 123 124 125 126 127 128 129 130 131 132 133 134 135 136
| #include <stdio.h> #include <stdlib.h>
#define true 1 #define false 0
typedef char ElemType; typedef int Bool;
typedef struct Node { ElemType data; struct Node *next; } stackLink;
stackLink * InitStack();
void DestroyStack(stackLink *s);
Bool StackEmpty(stackLink *s);
Bool StackFull(stackLink *s);
int StackLength(stackLink *s);
Bool Push(stackLink *s,ElemType e);
void Pop(stackLink *s,ElemType *e);
Bool GetTop(stackLink *s,ElemType *e);
void DispStack(stackLink *s);
int main() { ElemType e; stackLink *s; printf("(1)初始化链栈s\n"); s = InitStack(); printf("(2)链栈为%s\n",(StackEmpty(s) == 1?"空":"非空")); printf("(3)依次进链栈元素a,b,c,d,e\n"); Push(s,'a'); Push(s,'b'); Push(s,'c'); Push(s,'d'); Push(s,'e'); printf("(4)链栈为%s\n",(StackEmpty(s) == 1?"空":"非空")); printf("(5)链栈长度:%d\n",StackLength(s)); printf("(6)从链栈顶到链栈底元素:");DispStack(s); printf("(7)出链栈序列:"); while (!StackEmpty(s)) { Pop(s,&e); printf("%c ",e); } printf("\n"); printf("(8)链栈为%s\n",(StackEmpty(s) == 1?"空":"非空")); printf("(9)释放链栈\n"); DestroyStack(s); return 0; }
stackLink * InitStack() { stackLink *tmp = (stackLink *)malloc(sizeof(stackLink)); tmp->next = NULL; return tmp; }
Bool StackEmpty(stackLink *s) { if(s->next == NULL) return true; else return false; }
Bool Push(stackLink *s,ElemType e) { stackLink *tmp = (stackLink *)malloc(sizeof(stackLink)); tmp->data = e; tmp->next = s->next; s->next = tmp; }
void DispStack(stackLink *s) { stackLink *tmp; tmp = s->next; while(tmp != NULL){ printf("%c\t",tmp->data); tmp = tmp->next; } printf("\n"); }
int StackLength(stackLink *s) { int n = 0; stackLink *tmp; tmp = s->next; while(tmp != NULL){ n++; tmp = tmp->next; } return n; }
void Pop(stackLink *s,ElemType *e) { stackLink *tmp = s->next; *e = tmp->data; s->next = tmp->next; free(tmp); }
void DestroyStack(stackLink *s) { if(s != NULL) { stackLink *tmp = s->next,*q; while (tmp != NULL) { q = tmp; tmp = tmp->next; free(q); } free(s); } }
|