数据结构:栈部分——双栈共享空间

#include<iostream>

using namespace std;

const int MAX_CONT = 100;
enum stacktype { stack_1, stack_2 };

template<class Datatype>
class sqDoubleStack 
{
public:
	sqDoubleStack() { top1 = -1; top2 = MAX_CONT; }
	sqDoubleStack(const Datatype* a1, int num1, const Datatype* a2, int num2);
	~sqDoubleStack() {};
	bool push(stacktype,Datatype);
	Datatype pop(stacktype);
private:
	int top1, top2;
	Datatype data[MAX_CONT];
};

template<class Datatype>
sqDoubleStack<Datatype>::sqDoubleStack(const Datatype* a1, int num1, const Datatype* a2, int num2)
{
	top1 = -1;
	top2 = MAX_CONT;
	int i = 0;
	if (num1 + num2 < MAX_CONT) {
		while (num1--) {
			push(stack_1, a1[i++]);
		}
		i = 0;
		while (num2--) {
			push(stack_2, a2[i++]);
		}			
	}
}

template<class Datatype>
bool sqDoubleStack<Datatype>::push(stacktype temp, Datatype a) 
{
	if (top1 + 1 == top2)
		throw "Overflow";
	if (temp == stack_1) 
		data[++top1] = a;
	else if (temp == stack_2)
		data[--top2] = a;
	return true;
}

template<class Datatype>
Datatype sqDoubleStack<Datatype>::pop(stacktype temp)
{
	if (temp == stack_1) {
		return (data[top1--]);
	}
	else if (temp == stack_2) {
		return (data[top2++]);
	}
	throw "stacktype Err";
}

int main() 
{
	int a1[10] = { 1,2,3,4,5,7,6,8,9,10 };
	int a2[5] = { 1,2,3,4,5 };
	sqDoubleStack<int> doublestack(a1, 10, a2, 5);

	char a3[] = "dhwuhdwuhduhwud";
	char a4[] = "znxmncmnvbmbxznv1516546";
	sqDoubleStack<char> doublestack2(a3, strlen(a3)+1, a4, strlen(a4)+1);

	doublestack.push(stack_1, 55);
	cout << doublestack.pop(stack_1) << endl;

	doublestack.push(stack_2, 155);
	cout << doublestack.pop(stack_2) << endl;

	doublestack2.push(stack_1, 'a');
	cout << doublestack2.pop(stack_1) << endl;

	doublestack2.push(stack_2, 'b');
	cout << doublestack2.pop(stack_2) << endl;
	return 0;
}

说明一个问题:对于构造函数调用自身成员函数,是有依据的,首先:构造函数自身也是成员函数;其次:当执行构造函数的时候,对象的数据成员的内存已经分配完成;因此构造函数是能够调用其他函数的。

为保证两个栈共享时不会轻易溢出,该类算法适用于解决两个变量,其变化趋势总是相反的情况。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值