一个数组实现两个栈,常见的有两种方法:
(1)第一个栈:从左向有增长
第二个栈:从右向左增长
(2)采用交叉索引的方法,1号栈所占数组索引为0,2,4,6,8....
2号栈所占数组索引为1,3,5,7....
采用方法二代码如下:
#include<iostream>
using namespace std;
#define MAX_SIZE 100
template<class T>
class DoubleStack
{
public:
DoubleStack()
: _topindex1(-1), _topindex2(-2)
{
_array = new T[MAX_SIZE];
}
void push(const T& x,int type)
{
if (type == 0)
{
if (_topindex1 + 2 >= MAX_SIZE)
{
cout<<"stack is full!"<<endl;
}
else
{
_array[_topindex1] = x;
cout << x << "->";
_topindex1 += 2;
}
}
else
{
if (_topindex2 + 2 >= MAX_SIZE)
{
cout << "stack is full!" << endl;
}
else
{
_array[_topindex2] = x;
cout << x << "->";
_topindex2 += 2;
}
}
}
void pop(int type)
{
if (type == 0)
{
if (_topindex1 == -1)
{
cout << "stack is empty!" << endl;
}
else
{
_topindex1 -= 2;
cout << _array[_topindex1] << endl;
}
}
else
{
if (_topindex2 == -2)
{
cout << "stack is empty!" << endl;
}
else
{
cout << _array[_topindex2] << endl;
_topindex2 -= 2;
}
}
}
bool isEmpty()
{
if (_topindex == -1 || _topindex == -2)
{
return true;
}
return false;
}
const T& top(int type)
{
if (type == 0)
{
if (indextop1 == -1)
{
throw new Exception("stack is empty!");
}
return _array[topindex1];
}
else
{
if (indextop1 == -2)
{
throw new Exception("stack is empty!");
}
return _array[topindex2];
}
}
private:
T* _array;
size_t _topindex1;
size_t _topindex2;
};
void Test()
{
DoubleStack<int> s;
cout << "第一个栈入栈:" << endl;
s.push(0,0);
s.push(2,0);
s.push(4,0);
s.push(6,0);
cout <<endl<< "第二个栈入栈:" << endl;
s.push(1,1);
s.push(3,1);
s.push(5,1);
s.push(7,1);
cout <<endl<< "第一个栈出栈:" << endl;
s.pop(0);
s.pop(0);
s.pop(0);
s.pop(0);
}
int main()
{
Test();
return 0;
}