数据结构C语言实现----出栈操作

#include<stdio.h> #include<stdlib.h> typedef struct { char *base; char *top; int stacksize; }sqStack; ////////////////////////////////////// //创建一个栈 #define STACK_SIZE 100 void initstack(sqStack *stack ) { stack->base = (char*)malloc( STACK_SIZE * sizeof(char)); if (!stack->base) { exit(0); } stack->top = stack->base; stack->stacksize = STACK_SIZE; } //////////////////////////////////// //入栈操作 #define STACK_MORE 10 void Push(sqStack *stack , char c) { if (stack->top - stack->base > stack->stacksize) { stack->base = (char*)realloc(stack->base , (stack->stacksize + STACK_MORE) * sizeof(char)); if (!stack->base) { exit(0); } stack->top = stack->base + stack->stacksize; stack->stacksize = stack->stacksize + STACK_MORE; } *(stack->top) = c; stack->top++; } ////////////////////////////////////// //出栈操作 void Pop(sqStack *stack , char *c) { if (stack->base == stack->top) { return; } *c = *--(stack->top); } int main() { sqStack stack; char c=1; printf("请安任意键创建一个栈...\n"); getchar(); initstack(&stack); printf("创建成功!\n"); printf("请输入要压入栈的一个字符串(读取到0截至): "); while ((c = getchar()) != '\n') { //scanf("%c",&c); //fflush(stdin); if (c!='\n') { Push(&stack , c); } } printf("压入字符完成,正在打印字符串...\n"); for (size_t i = 0; i < (stack.top - stack.base); i++) { printf("%c",*(stack.base + i)); } putchar('\n'); printf("请输入要弹出几个字符:"); int k; scanf("%d",&k); while (k) { k--; Pop(&stack , &c); printf("字符%c已弹出!\n",c); } printf("弹出字符完成,正在打印字符串...\n"); for (size_t i = 0; i < (stack.top - stack.base); i++) { printf("%c",*(stack.base + i)); } putchar('\n'); return 0; }

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/zyyxsz.html