题解 | #【模板】栈#
【模板】栈
https://www.nowcoder.com/practice/104ce248c2f04cfb986b92d0548cccbf
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct stack {
int* data;
int top;
int size;
} stack;
void init(stack* st) {
st->data = (stack*)malloc(sizeof(stack) * 10);
st->top = 0;
st->size = 10;
}
void push(stack* st, int x) {
if (st->top == st->size) {
st->size *= 2;
int* temp = (int*)realloc(st->data, sizeof(stack) * st->size);
st->data = temp;
}
st->data[st->top] = x;
st->top++;
}
int pop(stack* st) {
if(st->top==0){
return -1;
}else{
st->top--;
return st->data[st->top];
}
}
int top(stack* st) {
if(st->top==0){
return -1;
}else{
return st->data[st->top - 1];
}
}
int main() {
stack st;
init(&st);
int n;
scanf("%d", &n);
for (int i = 0; i < n; i++) {
char op[50];
scanf("%s", op);
if (strcmp(op, "push") == 0) {
int x;
scanf("%d", &x);
push(&st, x);
} else if (strcmp(op, "top") == 0) {
int val = top(&st);
if (val == -1) {
printf("error\n");
}
else printf("%d\n",val);
} else if (strcmp(op, "pop") == 0) {
int val = pop(&st);
if (val == -1) {
printf("error\n");
}
else printf("%d\n",val);
}
}
return 0;
}
查看14道真题和解析