题解 | #【模板】栈#C语言非链式存储
【模板】栈
https://www.nowcoder.com/practice/104ce248c2f04cfb986b92d0548cccbf
#include <stdio.h> #include<string.h> #define maxsize 100000 typedef struct { int data[maxsize]; int top; } sqstack; // 初始化栈 void initstack(sqstack* S) { S->top = -1; } // 判断栈是否为空 int stackempty(sqstack* S) { if (S->top == -1) { return 0; } return 1; } // 入栈 int push(sqstack* S, int x) { if (S->top == maxsize - 1) { return 0; } S->data[++S->top] = x; return 1; } // 出栈 void pop(sqstack* S, int* x) { if (stackempty(S) == 0) { printf("error\n"); } else { *x = S->data[S->top--]; printf("%d\n", *x); } } // 读栈顶元素 void top(sqstack* S) { if (stackempty(S) == 0) printf("error\n"); else printf("%d\n", S->data[S->top]); } int main() { sqstack S; initstack(&S); int n; char s[1100]; scanf("%d", &n); int i = 0; while (i < n) { int k; scanf("%s %d", s, &k); if (strcmp(s, "push") == 0) { push(&S, k); } if (strcmp("pop", s) == 0) { pop(&S, &k); } if (strcmp("top", s) == 0) { top(&S); } i++; } return 0; }