C++设计算法实现两个栈共享存储空间的基本运算,初始化initstack_d(&S),入栈push(&S,i,e),出栈pop(&S,i,&e)操作。注意两个不同栈顶指针的设置

题目:
设计算法实现两个栈共享存储空间的基本运算,初始化initstack_d(&S),入栈push(&S,i,e),出栈pop(&S,i,&e)操作。注意两个不同栈顶指针的设置

实现代码:

#include <iostream>
#include<string.h>
using namespace std;
#define stacksize 1024

typedef struct 
{
	int data[stacksize];
	int top1, top2;
	//int bot1, bot2;
} doublestacks; //共享栈数据结构的结构体

void initdoublestack(doublestacks &s)
{
	s.top1 = -1;
	//s->bot1 = -1;
	s.top2 = stacksize;
	//s->bot2 = stacksize;
}//初始化栈

bool push_doublestack(doublestacks &s, int i, int e)
{
	if ((s.top1 + 1) != s.top2)
	{
		if (i == 1)
		{
			s.data[++s.top1] = e;
			cout << "1栈入栈成功" << endl;
		}
		else if (i == 2)
		{
			s.data[--s.top2] = e;
			cout << "2栈入栈成功" << endl;
		}
		return true;
	}
	else if ((s.top1 + 1) == s.top2)
	{
		cout << "存储空间已满" << endl;
		return false;
	}
}

bool pop_doublestack(doublestacks &s, int i, int &e)
{
	if (i == 1)
	{
		if (s.top1 == -1)
		{
			cout << "栈1为空" << endl;
			return false;
		}
		else
		{
			if (s.data[s.top1] != e)
			{
				cout << "出栈号数错误" << endl;
				return false;
			}
			else
			{
				e = s.data[s.top1--];
				cout << "1栈出栈成功" << endl;
				return true;
			}
		}
	}
	else if (i == 2)
	{
		if (s.top2 == stacksize)
		{
			cout << "栈2为空" << endl;
			return false;
		}
		else
		{
			if (s.data[s.top2] != e)
			{
				cout << "出栈号数错误" << endl;
				return false;
			}
			else
			{
				e = s.data[s.top2++];
				cout << "2栈出栈成功" << endl;
				return true;
			}

		}
	}
}

/*int clear(doublestack *&s)
{	if (!s)
	{	return 0;
	}
	s->top1 = 0;
	s->top2 = stacksize - 1;
	return 0;
}*/

int main()
{
	doublestacks s;
	initdoublestack(s);
	int n = 3, m = 6;
	for (int i = n; i <= m; i++)
	{
		push_doublestack(s, 1, i);
	}
	for (int i = n; i <= m; i++)
	{
		push_doublestack(s, 2, i);
	}
	for (int j = m; j >= n; j--)
	{
		pop_doublestack(s, 1, j);
	}
	for (int j = m; j >= n; j--)
	{
		pop_doublestack(s, 2, j);
	}
	return 0;
}

 

 

 

 

 

 

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值