#include <stdio.h>
#include <stdlib.h>
#include<string.h>
// 链式栈节点结构体
typedef struct Node {
int data; // 数据域
struct Node* next; // 指针域,指向下一个节点
} Node;
// 链式栈结构体
typedef struct Stack {
Node* top; // 栈顶指针
} Stack;
// 初始化链式栈
Stack* init() {
Stack* stack = (Stack*)malloc(sizeof(Stack)); // 分配内存空间
stack->top = NULL; // 栈顶指针初始化为NULL
return stack;
}
// 判断链式栈是否为空
int isEmpty(Stack* stack) {
return stack->top == NULL ? 1 : 0;
}
// 入栈操作
void push(Stack* stack, int data) {
Node* node = (Node*)malloc(sizeof(Node)); // 创建新节点
node->data = data; // 赋值
node->next =
stack->top; // 新节点的next指针指向原栈顶节点
stack->top = node; // 更新栈顶指针
}
// 出栈操作
void pop(Stack* stack) {
if (isEmpty(stack)) { // 如果栈为空则返回-1
printf("error\n"); //这段代码是可以优化的
return;
}
int data = stack->top->data; // 获取栈顶元素的值
Node* tmp = stack->top; // 保存栈顶节点指针
stack->top = stack->top->next;// 更新栈顶指针
free(tmp); // 释放节点空间
printf("%d\n", data); // 返回栈顶元素的值
}
// 获取栈顶元素
void peek(Stack* stack) {
if (isEmpty(stack)) { // 如果栈为空则返回-1
printf("error\n");
return;
}
printf("%d\n", stack->top->data); // 返回栈顶元素的值
}
// 测试代码
int main() {
Stack* stack = init(); // 初始化栈
int i, input, n = 0;
char s[10];
scanf("%d", &n);
while (n) {
scanf("%s", s);
if (strcmp(s, "push") == 0) {
scanf("%d", &input);
push(stack, input);
} else if (strcmp(s, "pop") == 0) {
pop(stack);
} else if (strcmp(s, "top") == 0) {
peek(stack);
}
n--;
}
return 0;
}