//堆栈就像个水桶
//现在咱们把两个水桶嘴对嘴
//和一个水桶的时候相比,两个水桶都装满的判断条件是两个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;
}
}