简单链栈练习

#include #include #include #define STACK_SIZE 100 typedef struct Node { char data; struct Node* Next; }StackNode; typedef struct { StackNode* TopNode; int top; }LinkStack; //初始化栈 LinkStack* Init_LinkStack() { LinkStack* s = (LinkStack*)malloc(sizeof(LinkStack)); assert(s != NULL); s->TopNode = NULL; s->top = -1; return s; } //判栈空 int LinkStack_Empty(LinkStack* s) { if (-1 == s->top) { return 1; } else return 0; } //判栈满 int LinkStack_Full(LinkStack* s) { if (s->top == (STACK_SIZE - 1)) { printf("栈已满!\n"); return 1; } else return 0; } //入栈 int Push_LinkStack(LinkStack* s, int x) { if (LinkStack_Full(s)) { printf("栈已满!"); return 0; } else { StackNode* p; p = (StackNode*)malloc(sizeof(StackNode)); assert(NULL != p); p->data = x; p->Next = s->TopNode; s->TopNode = p; s->top++; return 1; } } //出栈 int Pop_LinkStack(LinkStack* s, char* x) { StackNode* p; if (LinkStack_Empty(s)) { printf("栈已空!"); } else { *x = s->TopNode->data; p = s->TopNode; s->TopNode = s->TopNode->Next; s->top--; free(p); return 1; } } //得到栈顶元素 int Get_Top(LinkStack* s, char* x) { if (LinkStack_Empty(s)) { printf("栈已空!"); return 0; } else { *x = s->TopNode->data; return 1; } } //栈的大小 int Stack_Size(LinkStack* s) { return s->top + 1; } //清空栈 int Clear_Stack(LinkStack* s) { char* x = (char*)malloc(sizeof(char)); if (LinkStack_Empty(s)) return 1; else { while (s->top != -1) { Pop_LinkStack(s, x); } } } int main(int argc, char** argv) { LinkStack* s; char* x = (char*)malloc(sizeof(char)); s = Init_LinkStack(); //创建一个字符栈 printf("栈的压入!\n"); Push_LinkStack(s, 'c'); printf("%c ", s->TopNode->data); Push_LinkStack(s, 'b'); printf("%c ", s->TopNode->data); Push_LinkStack(s, 'a'); printf("%c \n", s->TopNode->data); printf("栈的弹出!\n"); Pop_LinkStack(s, x); printf("%c ", *x); Pop_LinkStack(s, x); printf("%c ", *x); Pop_LinkStack(s, x); printf("%c \n", *x); Pop_LinkStack(s, x); free(s); free(x); return 0; }

你可能感兴趣的:(c语言/数据结构)