#include <stdio.h>
#define STACK_MAX_NUM 100
typedef struct
{
int stack[STACK_MAX_NUM];
int top;
}stack_type;
void init_stack(stack_type* p)
{
p->top = 0;
}
void push(stack_type* p, int m, int x)
{
if (p->top == m)
{
printf("overflow!\n");
return;
}
p->top++;
p->stack[p->top - 1] = x;
}
int pop(stack_type* p, int m)
{
if (p->top == 0)
{
printf("underflow!\n");
return -1;
}
p->top--;
int x;
x = p->stack[p->top];
return x;
}
int top(stack_type* p)
{
if (p->top == 0)
{
return -1;
}
int x;
x = p->stack[p->top - 1];
return x;
}
int main()
{
stack_type stack;
init_stack(&stack);
int choice, value;
int m = STACK_MAX_NUM;
while (1)
{
printf("\n栈操作菜单:\n");
printf("1. 入栈 (Push)\n");
printf("2. 出栈 (Pop)\n");
printf("3. 查看栈顶元素 (Top)\n");
printf("4. 退出程序\n");
printf("请输入你的选择 (1-4): ");
scanf("%d", &choice);
switch (choice)
{
case 1:
printf("请输入要压入栈的数字: ");
scanf("%d", &value);
push(&stack, m, value);
break;
case 2:
value = pop(&stack, m);
if (value != -1)
{
printf("弹出的元素是: %d\n", value);
}
break;
case 3:
value=top(&stack);
if (value != -1) {
printf("栈顶元素是: %d\n", value);
}
break;
case 4:
printf("程序结束。\n");
return 0;
default:
printf("无效的选择,请重新输入。\n");
}
}
return 0;
}