//顺序栈基本运算
#include <stdio.h>
#include <stdlib.h>
#define MAXSIZE 20
typedef struct
{
char data[MAXSIZE]; //栈中元素存储空间
int top; //栈顶指针
}SeqStack;
void Init_SeqStack(SeqStack **s); //顺序栈初始化
int Empty_SeqStack(SeqStack *s); //判断栈是否为空
void Push_SeqStack(SeqStack *s, char x); //顺序栈元素入栈
void print(SeqStack *s); //顺序栈输出
void Pop_SeqStack(SeqStack *s, char *x); //将栈顶元素出栈,返回给x
void Top_SeqStack(SeqStack *s, char *x); //取顺序栈栈顶元素
int main()
{
SeqStack *s;
char x, *y = &x; //y是指向x 的指针,出栈元素经过y 传给变量x
Init_SeqStack(&s); //顺序栈初始化
if (Empty_SeqStack(s)) //判断是否为空
{
printf("Stack is empty!\n");
}
printf("Input data of stack:\n"); //顺序栈元素入栈
scanf("%c", &x);
while (x != '\n')
{
Push_SeqStack(s, x);
scanf("%c", &x);
}
printf("Output all data of stack:\n");
print(s); //输出顺序栈中的元素
Pop_SeqStack(s, y); //顺序栈元素出栈
printf("Output data of Pop stack:%c\n", *y); //输出出栈元素
printf("Output all data of stack:\n");
print(s); //输出出栈后顺序栈中的元素
Top_SeqStack(s, y); //读取顺序栈栈顶元素
printf("Output data of top stack:%c\n", *y); //输出读出的栈顶元素
printf("Output all data of stack:\n");
print(s); //输出当前的顺序栈中的元素
return 0;
}
void Init_SeqStack(SeqStack **s)
{
*s = (SeqStack *)malloc(sizeof(SeqStack)); //在主调函数中申请栈空间
(*s)->top = -1; //置栈空标志
}
int Empty_SeqStack(SeqStack *s)
{
if (s->top == -1) //栈为空时
{
return -1;
}
else
{
return 0;
}
}
void Push_SeqStack(SeqStack *s, char x)
{
if (s->top == MAXSIZE - 1)
{
printf("Stack is full!\n"); // 栈已满
}
else
{
s->top++;
s->data[s->top] = x; //元素x 压入栈*s 中
}
}
void print(SeqStack *s)
{
int i;
for (i = 0; i <= s->top; i++)
{
printf("%4c", s->data[i]);
}
printf("\n");
}
void Pop_SeqStack(SeqStack *s, char *x)
{ //将*s 中的栈顶元素出栈并通过参数x 返回给主调函数
if (s->top == -1)
{
printf("Stack is empty"); //栈为空
}
else
{
*x = s->data[s->top]; //栈顶元素出栈
s->top--;
}
}
void Top_SeqStack(SeqStack *s, char *x)
{
if (s->top == -1)
{
printf("Stack is empty!\n"); //栈为空
}
else
{
*x = s->data[s->top]; //取栈顶元素值
}
}
顺序栈基本运算
最新推荐文章于 2022-05-03 21:21:49 发布