```
#include<stdio.h>
#include<stdlib.h>
struct Zimu
{
char letter;
struct Zimu* next;
};
struct Stack
{
struct Zimubase;//栈底
struct Zimutop;//栈顶
int Size;
};//栈类型
struct Zimu* creatNode(char letter)//创建节点
{
struct Zimu* newNode = (struct Zimu*)malloc(sizeof(struct Zimu));
newNode->letter = letter;
newNode->next = NULL;
return newNode;
}
//初始化
int initstack(struct Stack* S)
{
S->base = (struct Zimu*)malloc(sizeof(struct Zimu));
if(!S->base)exit(-1);
S->top = S->base;
S->Size = 0;
return 0;
}
void push(struct Stack * S)//进栈
{
char letter;
printf("请输入字母\n");
scanf(" %c", &letter); // 使用 " %c" 读取字符,防止上一行结尾的换行符干扰
struct Zimu* newnode = creatNode(letter);
newnode->next = S->top;
S->top = newnode;
S->Size++;
}
int top(struct Stack* S)//获取栈顶元素
{
if(S->Size == 0)
{
printf("栈为NULL\n");
return 0;
}
return S->top->letter;
}
void pop(struct Stack* S)//出栈
{
if(S->Size == 0)
{
printf("栈为NULL\n");
}
else
{
struct Zimu* nextnode = S->top->next;
free(S->top);
S->top = nextnode;
S->Size--;
}
}
int empty(struct Stack* S)
{
if(S->Size == 0)
return 0;
return 1;
}
char letter;
int main()
{
int t;
struct Stack* S;
initstack(S);
push(S);
printf("请选择你要进行的操作:\n");
scanf("%d", &t);
do
{
switch(t)
{
case 1: push(S);
break;
case 2: pop(S);
break;
case 3: printf("%c", S->top->letter); // 使用 %c 打印字符
pop(S);
break;
default :
break;
}
}
while(t>=1&&t<=3);
return 0;
}```