顺序栈基本运算

//顺序栈基本运算
#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];                    //取栈顶元素值
	}
}

  • 1
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值