题解 | #【模板】栈#
【模板】栈
https://www.nowcoder.com/practice/104ce248c2f04cfb986b92d0548cccbf
#include <stdio.h>
#include <string.h>
// #include <stdlib.h>
#define MAXSIZE 100000
typedef struct{
int stack[MAXSIZE];
int top;
}Stack, *LStack;
void push(LStack s, int x){
s->stack[s->top++] = x;
}
void pop(LStack s){
if(!(s->top)){
printf("error\n");
}
else {
printf("%d\n", s->stack[--s->top]);
}
}
void top(LStack s){
if(!(s->top)){
printf("error\n");
}
else {
printf("%d\n", s->stack[s->top - 1]);
}
}
int main() {
int n;
scanf("%d", &n);
Stack stack;
LStack lstack = &stack;
stack.top = 0;
char operation[5];
int nums;
for (int i = 0; i < n; i++) {
scanf("%s %d", operation, &nums);
if (!(strcmp(operation, "push"))) {
push(lstack, nums);
}
else if (!(strcmp(operation, "pop"))) {
pop(lstack);
}
else if (!(strcmp(operation, "top"))) {
top(lstack);
}
}
return 0;
}