题解 | #【模板】栈#
【模板】栈
https://www.nowcoder.com/practice/104ce248c2f04cfb986b92d0548cccbf
#include <stdio.h> #include <stdlib.h> #include <string.h> #define MAX 100001 typedef struct Stack{ int data[MAX]; int top; }* PStack,Stack; PStack getStack(){ PStack Lstack = (PStack)malloc(sizeof(Stack)); Lstack->top = 0; return Lstack; } void push(PStack stack,int val){ stack->data[stack->top] = val; stack->top++; } int pop(PStack stack){ if (stack->top == 0) { return -1; } stack->top--; return stack->data[stack->top]; } int top(PStack stack){ if (stack->top == 0) { return -1; } return stack->data[stack->top-1]; } int main() { PStack Lstack = getStack(); int count = 0; scanf("%d",&count); char* str = (char *)malloc(6*sizeof(char)); for (int i = 0; i < count; i++) { scanf("%s",str); if (!strcmp(str,"push")) { int num=0; scanf("%d",&num); push(Lstack,num); }else if (!strcmp(str,"pop")) { int num=0; if ((num = pop(Lstack))==-1) { printf("error\n"); }else { printf("%d\n",num); } }else if (!strcmp(str,"top")) { int num=0; if ((num = top(Lstack))==-1) { printf("error\n"); }else { printf("%d\n",num); } } } return 0; }