C++实现双栈结构(一个顺序表中使用两个栈)
生活随笔
收集整理的這篇文章主要介紹了
C++实现双栈结构(一个顺序表中使用两个栈)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
因為平常棧中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; }總結
以上是生活随笔為你收集整理的C++实现双栈结构(一个顺序表中使用两个栈)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 怕热,出汗多,黑眼圈,浑身无力
- 下一篇: Java面向对象编程(基础部分)