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 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155
| #include <stdio.h> #include <malloc.h> #include <assert.h> typedef int ElemType;
typedef struct StackNode { ElemType data; struct StackNode *next; }ListNode,*pNode;
typedef struct ListStack { pNode top; size_t size; }ListStack;
void InitStack(ListStack *s) { s->top=(StackNode*)malloc(sizeof(StackNode)); assert(s->top!=NULL); s->top = NULL; s->size=0; }
bool IsEmptyStack(ListStack *s) { if(s->size == 0) return true; else return false; }
void PushStack(ListStack *s, ElemType x) { StackNode *p=(StackNode*)malloc(sizeof(StackNode)); assert(p!=NULL); p->data = x; p->next = s->top; s->top = p; s->size++; }
void PopStack(ListStack *s, ElemType *v) { StackNode *p=s->top; *v=s->top->data; s->top=s->top->next; free(p); s->size--; }
void ShowStack(ListStack *s) { StackNode *p=s->top; printf("链栈中的数据元素:"); while(p!=NULL) { printf("%d->",p->data); p = p->next; } printf("\n"); }
void GetTopStack(ListStack *s,ElemType *v) { if(s->top==NULL) return; else *v=s->top->data; }
int LengthStack(ListStack *s) { return s->size; }
void ClearStack(ListStack *s) { StackNode *p=s->top; while(p!=NULL) { s->top=p->next; free(p); p=s->top; } s->top = NULL; s->size = 0; }
void DestroyStack(ListStack *s) { ClearStack(s); free(s->top); s->top=NULL; }
void main() { ListStack st; ElemType e; InitStack(&st); if(IsEmptyStack(&st)) printf("栈为空,初始化成功\n\n"); else printf("栈非空!\n\n"); printf("入栈\n"); for(int i=0;i<5;i++) { PushStack(&st,i); } ShowStack(&st); printf("\n"); int k=LengthStack(&st); printf("栈的长度为:%d \n\n",k); GetTopStack(&st,&e); printf("栈顶元素为:%d \n",e); printf("\n"); printf("出栈\n"); PopStack(&st,&e); printf("出栈的元素为:%d \n",e); ShowStack(&st); printf("\n"); PopStack(&st,&e); printf("出栈的元素为:%d \n",e); ShowStack(&st); printf("\n"); PopStack(&st,&e); printf("出栈的元素为:%d \n",e); ShowStack(&st); printf("\n"); PopStack(&st,&e); printf("出栈的元素为:%d \n",e); ShowStack(&st); printf("\n"); PopStack(&st,&e); printf("出栈的元素为:%d \n",e); ShowStack(&st); printf("\n"); PopStack(&st,&e); printf("出栈的元素为:%d \n",e); ShowStack(&st); ClearStack(&st); DestroyStack(&st); }
|