仅代码,图解后续完善
#include <iostream>
using namespace std;
#define DataType char
const int STACK_SIZE = 100;
class BothStack{
private:
DataType data[STACK_SIZE];
int top1 , top2;
public:
BothStack();
~BothStack();
void push(int,DataType);
DataType pop(int,char);
DataType getTop(int);
bool isEmpty(int);
bool isFull();
void displayStack1();
void displayStack2();
class Empty{};
class Full{};
};
BothStack::BothStack(){
top1 = -1;
top2 = STACK_SIZE;
}
BothStack::~BothStack(){
delete[] data;
}
void BothStack::push(int s , DataType ch){
switch(s){
case 1:
if(isFull()){
throw BothStack::Full();
}else{
data[++top1] = ch;
}
break;
case 2:
if(isFull()){
throw BothStack::Full();
}else{
data[--top2] = ch;
}
}
}
DataType BothStack::pop(int s , char ch){
switch(s){
case 1:
if(isEmpty(s)){
throw BothStack::Empty();
}else{
ch = data[top1--];
}
break;
case 2:
if(isEmpty(s)){
throw BothStack::Empty();
}else{
ch = data[top2++];
}
}
return ch;
}
DataType BothStack::getTop(int s){
switch(s){
case 1:
if(isEmpty(s)){
throw BothStack::Empty();
}else{
return data[top1];
}
break;
case 2:
if(isEmpty(s)){
throw BothStack::Empty();
}else{
return data[top2];
}
}
}
bool BothStack::isEmpty(int s){
switch(s){
case 1:
if(top1 == -1){
return true;
}else{
return false;
}
break;
case 2:
if(top2 == STACK_SIZE){
return true;
}else{
return false;
}
}
}
bool BothStack::isFull(){
if(top2 == top1+1){
return true;
}else{
return false;
}
}
void BothStack::displayStack1(){
cout << "栈1中元素:";
for(int i = 0 ; i <= top1 ; i ++){
cout << data[i];
}
cout << endl;
}
void BothStack::displayStack2(){
cout << "栈2中元素:";
for(int i = STACK_SIZE - 1 ; i >= top2 ; i --){
cout << data[i];
}
cout << endl;
}
int main(void){
BothStack bs;
try{
bs.push(1,'a');
bs.push(1,'b');
bs.push(1,'c');
bs.displayStack1();
}catch(BothStack::Full){
cout << "当前栈满!" << endl;
}
try{
bs.push(2,'x');
bs.push(2,'y');
bs.push(2,'z');
bs.displayStack2();
}catch(BothStack::Full){
cout << "当前栈满!" << endl;
}
try{
char c;
char c1 = bs.pop(1,c);
cout << "当前弹出" << c1 <<endl;
bs.displayStack1();
}catch(BothStack::Empty){
cout << "当前栈空!" << endl;
}
return 0;
}