因为平常栈中push的数据不会太多,为了节约空间,所以可以在一个顺序表中使用两个栈
结构图:
在这里我会留一个空间用来判断栈是否满!
#include <iostream>
using namespace std;
typedef int ElemType;class DoubleStack
{
private:ElemType *top_1;ElemType *base_1;ElemType *top_2;ElemType *base_2;public:DoubleStack(int n = 3){base_1 = new ElemType[n];top_1 = base_1;top_2 = top_1 + n - 1;base_2 = top_2;}bool push_1(ElemType e){if (top_1 == top_2){cout << "Stack_1 has fullen" << endl;return false;}*top_1 = e;top_1++;return true;}bool push_2(ElemType e){if (top_2 == top_1){cout << "Stack_2 has fullen" << endl;return false;}*top_2 = e;top_2--;return true;}bool pop_1(ElemType &e){if (top_1 == base_1){cout << "Stack_1 is empty" << endl;return false;}top_1--;e = *top_1;return true;}bool pop_2(ElemType &e){if (top_2 == base_2){cout << "Stack_2 is empty" << endl;return false;}top_2++;e = *top_2;return true;}bool isEmpty_1(){if (top_1 == base_1){return true;}return false;}bool isEmpty_2(){if (top_2 == base_2){return true;}return false;}bool getTop_1(ElemType &e){if (isEmpty_1()){cout << "Stack_1 is empty" << endl;return false;}e = *(top_1 - 1);return true;}bool getTop_2(ElemType &e){if (isEmpty_2()){cout << "Stack_2 is empty" << endl;return false;}e = *(top_2 + 1);return true;}void printStack_1(){if (isEmpty_1()){cout << "Stack_1 is empty" << endl;return;}ElemType *p = base_1;cout << "底在前顶在后:" << endl;while (p != top_1){cout << *p << " ";p++;}cout << endl;}void printStack_2(){if (isEmpty_2()){cout << "Stack_2 is empty" << endl;return;}ElemType *p = base_2;cout << "底在前顶在后:" << endl;while (p != top_2){cout << *p << " ";p--;}cout << endl;}};int main()
{DoubleStack s(10);for (int i = 0; i < 7; i++){s.push_1(i);}s.push_2(3);s.push_2(4);s.push_1(5);s.printStack_1();s.printStack_2();if (s.isEmpty_1()){cout << "yes" << endl;}else cout << "no" << endl;if (s.isEmpty_2()){cout << "yes" << endl;}else cout << "no" << endl;return 0;
}