一个数组实现两个栈(两种方法)
1.数组两边作栈底,往中间走走
#pragma once
#define MAX_SIZE 8
typedef int DataType;
template <class T> //模板类
class DoubleStack
{
public:
DoubleStack()
:_top1(0),
_top2(MAX_SIZE-1)
{
_array = new T[MAX_SIZE];
}
bool _IsFull() //当两个栈顶相遇时,数组满了
{
if (_top2 - _top1 == 0)
return false;
else
return true;
}
void _push(DataType index, const T& data)//压栈
{
if (_IsFull())
{
if (index == 0)
{
_array[_top1] = data;
_top1++;
}
else if (index == 1)
{
_array[_top2] = data;
_top2--;
}
else
return;
}
else
cout << "stack is overflow" << endl;
}
void _pop(DataType index) //出栈
{
if (index == 0)
{
if (_top1 == 0)
{
cout << "栈1为空" << endl;
}
else
{
_top1--;
}
}
else if (index == 1)
{
if (_top2 == MAX_SIZE)
{
cout << "栈2为空" << endl;
}
else
{
_top2++;
}
}
else
return ;
}
void _print()//
{
int i = 0;
int j = 0;
for (i = 0; i < _top1; i++)
{
cout << _array[i] << "->";
}
cout << " ";
for (j = MAX_SIZE-1; j > _top2; j--)
{
cout << _array[j] << "->";
}
cout << endl;
}
private:
T* _array;//数组指针
size_t _top1;//第一个栈底
size_t _top2;//第二个栈底
};
测试
#include<iostream>
#include<stdlib.h>
using namespace std;
#include"DoubleStack.h"
void test1()
{
DoubleStack<int> s1;
s1._IsFull();
s1._push(0,1);
s1._push(0, 2);
s1._push(0, 2);
s1._push(0, 3);
/*s1._push(0, 4);
s1._push(0, 4);
s1._push(0, 4);*/
s1._push(1, 1);
s1._push(1, 2);
s1._push(1, 2);
s1._print();
s1._push(1, 3);
s1._push(1, 4);
s1._print();
s1._pop(0);
s1._pop(0);
s1._pop(0);
s1._pop(0);
s1._pop(0);
s1._print();
s1._pop(1);
s1._pop(1);
s1._print();
}
int main()
{
test1();
system("pause");
return 0;
}