《天勤数据结构》笔记——使用两个栈实现共享栈实现(C/C++)

共享栈为空的状态,左右两栈的栈顶指针都在两端,也就是各自栈的栈底

代码当中测试栈满的时候的状态图

 共享栈的数据结构

typedef struct{
	int elem[maxSize];
	int top[2];
}SqStack;

入共享栈的操作,因为共享栈是由两个栈组成的,因此我们在入栈的时候需要选择入栈的编号,也就是stNo,同时要注意栈满的特殊情况

int push(SqStack &st, int stNo, int x){
	if (st.top[0]+1<st.top[1]){ //先判断栈是否是满的
		if (stNo==0){
			++(st.top[0]);
			st.elem[st.top[0]]=x;
			return 1; //入栈成功
		}else if (stNo==1){
			--(st.top[1]);
			st.elem[st.top[1]]=x;
			return 1;
		}else
			return -1;
	}else
		return 0; //入栈失败
}

出栈操作,同样需要指定出栈的编号,同时还需要处理指定的栈栈中元素是否为空的特殊情况

int pop(SqStack &st, int stNo, int &x){
	if (stNo==0){
		if (st.top[0]!=-1){ //验证栈是否为空
			x=st.elem[st.top[0]];
			--(st.top[0]);
			return 1; //出栈成功
		}else
			return 0; //出栈失败
	}else if (stNo==1){
		if (st.top[1]!=maxSize){
			x=st.elem[st.top[1]];
			++(st.top[1]);
			return 1;
		}else
			return 0; //出栈失败
	}else
		return -1; //栈编号输入错误
}

判断共享栈是否是满的

int isEmpty(SqStack st){
	if (st.top[0]+1==st.top[1])
		return 1;
	else
		return 0;
}

我只写了这三种基本操作,此外还可以自行添加返回栈顶元素的操作

下为完整的代码,可直接运行

#include <stdio.h>

#define maxSize 5

typedef struct{
	int elem[maxSize];
	int top[2];
}SqStack;

//初始化
void init(SqStack &st){
	st.top[0]=-1;
	st.top[1]=maxSize;
}

//入栈操作
//stNo是栈的编号,x是入栈元素
int push(SqStack &st, int stNo, int x){
	if (st.top[0]+1<st.top[1]){ //先判断栈是否是满的
		if (stNo==0){
			++(st.top[0]);
			st.elem[st.top[0]]=x;
			return 1; //入栈成功
		}else if (stNo==1){
			--(st.top[1]);
			st.elem[st.top[1]]=x;
			return 1;
		}else
			return -1;
	}else
		return 0; //入栈失败
}

//出栈
int pop(SqStack &st, int stNo, int &x){
	if (stNo==0){
		if (st.top[0]!=-1){ //验证栈是否为空
			x=st.elem[st.top[0]];
			--(st.top[0]);
			return 1; //出栈成功
		}else
			return 0; //出栈失败
	}else if (stNo==1){
		if (st.top[1]!=maxSize){
			x=st.elem[st.top[1]];
			++(st.top[1]);
			return 1;
		}else
			return 0; //出栈失败
	}else
		return -1; //栈编号输入错误
}


//判断是否栈满,1为满,0为不满
int isEmpty(SqStack st){
	if (st.top[0]+1==st.top[1])
		return 1;
	else
		return 0;
}

//打印栈
void printStack(SqStack st){
	printf ("当前栈中元素是:");
	for (int i=0; i<=st.top[0]; i++){
		printf ("%d ", st.elem[i]);
	}
	for (int i=st.top[1]; i<maxSize; i++){
		printf ("%d ", st.elem[i]);
	}
	printf ("\n");
}


int main(){
	SqStack st;
	init(st);
	push(st, 0, 5);
	push(st, 0, 2);
	push(st, 0, 3);
	push(st, 1, 6);
	push(st, 1, 9);
	push(st, 1, 8);
	if (isEmpty(st)){
		printf ("栈满!\n");
	}
	int x;
	pop(st, 1, x);
	printf ("出栈元素是:%d\n", x);
	printStack(st);
	return 0;
}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值