双栈共享存储空间(C++代码实现)
生活随笔
收集整理的這篇文章主要介紹了
双栈共享存储空间(C++代码实现)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
理論部分
理論來源:b站up主:跟懶貓老師快樂數據結構
C++代碼
#include<iostream> using namespace std; const int STACKSIZE = 6; //兩棧共享存儲空間編程 //使用類模板編程 template<class DataType> class BothStack { private:DataType *data;//屬性,順序棧,數組int top1, top2;//屬性,top1指向棧1的棧頂,top2指向棧2的棧頂int capacity;//屬性,棧的容量 public:BothStack();//無參構造函數BothStack(int size);//有參構造函數~BothStack();//析構函數DataType getTop(int num);//彈出棧頂元素,num表明對棧1操作,還是對棧2操作DataType Pop(int num);//出棧void Push(int num, DataType elem);//入棧bool isFull();//判斷棧滿bool isEmpty(int num);//判斷棧空class IndexError{};//定義內部異常類class Empty{};class Full{}; };template<class DataType> BothStack<DataType>::BothStack() {data = new DataType[STACKSIZE];top1 = -1;top2 = STACKSIZE;capacity = STACKSIZE; }template<class DataType> BothStack<DataType>::BothStack(int size) {data = new DataType[size];top1 = -1;top2 = size;capacity = size; }template<class DataType> BothStack<DataType>::~BothStack() {delete[] data; }template<class DataType> DataType BothStack<DataType>::getTop(int num) {if (num == 1){//對棧1進行操作if (isEmpty(num)){throw Empty();}else{return data[top1];}}else if (num == 2){//對棧2進行操作if (isEmpty(num)){throw Empty();}else{return data[top2];}}else{throw IndexError();} }template<class DataType> DataType BothStack<DataType>::Pop(int num) {if (num == 1){//對棧1進行操作if (isEmpty(num)){throw Empty();}else{return data[top1--];}}else if (num == 2){//對棧2進行操作if (isEmpty(num)){throw Empty();}else{return data[top2++];}}else{throw IndexError();} }template<class DataType> void BothStack<DataType>::Push(int num, DataType elem) {if (isFull()){throw Full();}else {if (num == 1){data[++top1] = elem;}else if (num == 2){data[--top2] = elem;}else {throw IndexError();}} } template<class DataType> bool BothStack<DataType>::isFull() {if (top2 == top1 +1){return true;}return false; } template<class DataType> bool BothStack<DataType>::isEmpty(int num) {if (num == 1){if (top1 == -1){return true;}return false;}else if (num == 2){if (top2 == capacity){return true;}return false;}else{throw IndexError();} } int main() {BothStack<char> bs1;//棧1中依次壓入'a','b','c'//棧2中依次壓入'z','x','y'//棧3中壓入'z',拋出異常//try--catch捕獲異常對象try {bs1.Push(1, 'a');bs1.Push(1, 'b');bs1.Push(1, 'c');bs1.Push(2, 'z');bs1.Push(2, 'y');bs1.Push(2, 'x');bs1.Push(2, 'w');}catch (BothStack<char>::Full){cout << "Stack Full!!!" << endl;}catch (BothStack<char>::IndexError){cout << "Index Error!!!" << endl;}try {cout << bs1.Pop(1) << endl;cout << bs1.Pop(1) << endl;cout << bs1.Pop(1) << endl;cout << bs1.Pop(2) << endl;cout << bs1.Pop(2) << endl;cout<<bs1.Pop(2)<<endl;cout << bs1.Pop(2) << endl;}catch (BothStack<char>::Empty){cout << "Stack Empty!!!"<< endl;}catch (BothStack<char>::IndexError){cout << "Index Error!!!" << endl;} }運行結果
棧的大小為6
總結
以上是生活随笔為你收集整理的双栈共享存储空间(C++代码实现)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: c#打印,输出一句话
- 下一篇: s3c2440移植MQTT