DS_共享堆栈C++实现

//堆栈就像个水桶
//现在咱们把两个水桶嘴对嘴
//和一个水桶的时候相比,两个水桶都装满的判断条件是两个top指针相邻
//还是因为懒,不说具体的了

// DS_ShareStack.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include<iostream>
using namespace std;

template<class T>
class ShareStack
{
public:
	ShareStack(int max0 = 10) { max = max0 - 1; topFront = -1; topBack = max0; p = new T[max0]; }
	~ShareStack() { delete[] p; cout << "succeed to spare the space" << endl; }
	bool pushN(int barrel, T data);
	T popN(int barrel);
private:
	int topFront, topBack;
	int max;
	T *p;
};

int main()
{
	ShareStack<int> stack(3);
	stack.pushN(0, 1);
	stack.pushN(1, 2);
	stack.pushN(0, 3);
	stack.pushN(0, 4);

	cout << "the middle one is " << stack.popN(0) << endl;
	cout << "the first one is " << stack.popN(0) << endl;
	cout << "the last one is " << stack.popN(1) << endl;
	//stack.popN(1);

	system("pause");
    return 0;
}

template<class T>
bool ShareStack<T>::pushN(int barrel, T data)
{
	if (topBack == topFront + 1) { cerr << "It's full!" << endl; return false; }
	if (0 == barrel)
		p[++topFront] = data;
	else
		p[--topBack] = data;
	return true;
}

template<class T>
T ShareStack<T>::popN(int barrel)
{
	switch (barrel)
	{
	case 0:
		if (-1 == topFront) { cerr << "nothing to pop in the front!" << endl; exit(-1); }
		return p[topFront--];
	case 1:
		if (max + 1 == topBack) { cerr << "nothing to pop in the back!" << endl; exit(-1); }
		return p[topBack++];
	default:
		break;
	}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值