#include <stdio.h>
#include <string.h>
#include <stdlib.h>
typedef struct StackNode {
int x;
struct StackNode* next;
} StackNode;
typedef StackNode* LinkStack;
void StackInit(LinkStack *s);
void Distop(LinkStack *s);
void RemovePop(LinkStack *s);
void PushTop(LinkStack *s, int x);
int main() {
int n, x;
LinkStack s = NULL;
char str[5];
scanf("%d", &n);
StackInit(&s);
for (int i = 0; i < n; i++) {
scanf("%s %d", str, &x); // 注意这里使用 &x
if (strcmp(str, "pop") == 0) {
RemovePop(&s);
} else if (strcmp(str, "top") == 0) {
Distop(&s);
} else {
PushTop(&s, x);
}
}
return 0;
}
void StackInit(LinkStack *s){
*s = NULL;
}
void Distop(LinkStack *s) {
if (*s == NULL) {
printf("error\n");
} else {
printf("%d\n", (*s)->x);
}
return;
}
void RemovePop(LinkStack *s) {
if (*s == NULL) {
printf("error\n");
} else {
printf("%d\n",(*s)->x);
LinkStack p = *s;
*s = (*s)->next;
free(p);
p = NULL; // 释放后将指针设置为 NULL 避免悬挂指针
}
return;
}
void PushTop(LinkStack *s, int y){
LinkStack newnode = (LinkStack)malloc(sizeof(StackNode));
newnode->x = y;
newnode->next = *s;
*s = newnode;
}