数据结构 - 顺序栈的基本操作实现

1.初始化一个空栈S: void InitStack(SqStack &S)

//初始化
void InitStack(SqStack &S) {
	S.top = -1;	
}

2.判断S栈是否为空:bool StackEmpty(SqStack S)

//判空
bool StackEmpty(SqStack S) {
	if (S.top == -1)
	{
		return true;
	}
	else
	{
		return false;
	}
}

3.进栈:bool Push(SqStack &S, int x)

//进栈
bool Push(SqStack &S, int x) {
	if (S.top == MAXSIZE-1)
	{
		return false;	//栈满
	}
	S.data[++S.top] = x;	//top指针先+1,再入栈
	return true;
}

4.出栈:bool Pop(SqStack &S, int &x)

//出栈
bool Pop(SqStack &S, int &x) {
	if (S.top == -1)
	{
		return false;	//空栈,无法出栈
	}
	x = S.data[S.top--];		//先出栈,top指针再-1,因为这里用的是静态数组,会自动释放掉
	return true;
}

5.读栈顶元素:bool GetTop(SqStack &S, int &x)

//读栈顶元素
bool GetTop(SqStack &S, int &x) {
	if (S.top == -1)
	{
		return false;	//栈空
	}
	x = S.data[S.top];
	return true;
}

6.销毁栈:bool DestroyStack(SqStack &S)

//销毁栈
bool DestroyStack(SqStack &S) {
	while (S.top != -1);
	{
		S.data[S.top--];
	}
	return true;
}

测试代码

#include<stdio.h>
#include<stdlib.h>

#define MAXSIZE 50	
typedef struct {
	int data[MAXSIZE];
	int top;		//栈顶指针
}SqStack;


//初始化
//判空
//进栈
//出栈
//读栈顶元素
//销毁栈


int main() {

	SqStack S;	//申明一个顺序栈(分配空间)
	InitStack(S);	//初始化
	//判空
	if (StackEmpty(S))		
	{
		printf("S现在是个空栈\n");
	}
	//入栈
	if (Push(S,2))
	{
		printf("2入栈成功!\n");
	}
	if (Push(S, 3))
	{
		printf("3入栈成功!\n");
	}
	//取栈顶
	int top;	//定义变量获取栈顶数字
	if (GetTop(S,top))
	{
		printf("Now,The top of this stack is:%d\n", top);
	}
	//出栈
	int t;
	if (Pop(S,t))
	{
		printf("%d出栈\n",t);
	}
	if (Pop(S, t))
	{
		printf("%d出栈\n", t);
	}
	//判空
	if (StackEmpty(S))
	{
		printf("S现在是个空栈\n");
	}
	//销毁栈
	if (DestroyStack(S))
	{
		printf("S栈已被销毁\n");
	}
	return 0;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Neo_LJH

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值