#include <stdio.h>
#include <stdlib.h>
typedef struct node
{
char data;
struct node *next;
}StackNode; //链栈元素类型
void Init_LinkStack(StackNode **s); //链表初始化
int Empty_LinkStack(StackNode *s); //判断链表是否为空
void Push_LinkStack(StackNode **top, char x); //链栈元素入栈
void Pop_LinkStack(StackNode **top, char *x); //链栈元素出栈
void print(StackNode *p); //链栈输出
int main()
{
StackNode *s;
char x, *y = &x; //出栈元素经指针y传给x
Init_LinkStack(&s); //链栈初始化
if (Empty_LinkStack(s)) //判断链栈是否为空
{
printf("Stack is empty!\n");
}
printf("Input any string:\n"); //链栈元素入栈
scanf("%c", &x);
while (x != '\n')
{
Push_LinkStack(&s, x);
scanf("%c", &x);
}
printf("Output string:\n");
print(s); //链栈输出
printf("Output stack:\n");
Pop_LinkStack(&s, y); //链栈元素出栈
printf("Element of Output stack is %c\n", *y); //输出元素出栈
printf("Output string:\n");
print(s); //链栈输出
return 0;
}
void Init_LinkStack(StackNode **s) //链栈初始化
{
*s = NULL;
}
int Empty_LinkStack(StackNode *s) //判断链栈是否为空
{
if (s == NULL)
{
return 1;
}
else
{
return 0;
}
}
void Push_LinkStack(StackNode **top, char x) //链栈元素入栈
{
StackNode *p;
p = (StackNode *)malloc(sizeof(StackNode)); //生成存放链栈元素的空间
p->data = x;
p->next = *top; //新生成的栈顶元素*p其后继为原栈顶元素**top
*top = p; //栈顶指针*top指向新的栈顶元素*p
}
void Pop_LinkStack(StackNode **top, char *x) //链表元素出栈
{
StackNode *p;
if (*top == NULL)
{
printf("Stack is empty!\n"); //栈为空
}
else
{
*x = (*top)->data; //栈顶怨怒是经指针x传给对应的变量
p = *top;
*top = (*top)->next; //栈顶指针*top指向出栈后的新栈顶元素
free(p);
}
}
void print(StackNode *p) //链栈输出
{
while (p != NULL)
{
printf("%c", p->data);
p = p->next;
}
printf("\n");
}
链栈
最新推荐文章于 2022-08-17 11:17:33 发布