栈实验(两栈共享空间)
两个栈共享一个存储空间,该方法对于两个栈对空间需求刚好相反时很有用,即一个栈增大,另一个栈必然减小的情况
头文件
#pragma once
const int STACKSIZE = 100;
class BothStack
{
public:
BothStack() { //初始化两个空栈
top1 = -1; //栈1的栈顶游标
top2 = STACKSIZE; };//栈2的栈顶游标
~BothStack() {};
void push(int i, int x);//i压栈x
void pop(int i);//i出栈
int getTop(int i);//返回i栈的栈顶元素
bool empty(int i);//返回i栈是否尾空
private:
int data[STACKSIZE];//两栈共用的空间
int top1, top2;//两栈游标
};
源文件
#include "BothStack.h"
void BothStack::push(int i, int x) {
switch (i)
{
case 1:
if (top1 == top2-1)throw"栈满溢出";
top1++;
data[top1] = x;
break;
case 2:
if (top1 == top2-1)throw"栈满溢出";
top2--;
data[top2] = x;
break;
default:
break;
}
}
void BothStack::pop(int i) {
switch (i)
{
case 1:
if (top1 == -1)throw"栈空下溢";
top1--;
break;
case 2:
if (top2 == STACKSIZE)throw"栈空下溢";
top2++;
break;
default:
break;
}
}
bool BothStack::empty(int i) {
switch (i)
{
case 1:
if (top1 == -1)return true;
return false;
break;
case 2:
if (top2 == STACKSIZE)return true;
return false;
break;
default:
break;
}
}
int BothStack::getTop(int i) {
switch (i)
{
case 1:
return data[top1];
break;
case 2:
return data[top2];
break;
default:
break;
}
}
测试文件
#include<iostream>
using namespace std;
#include"BothStack.h"
int main() {
BothStack st;
cout << "判断栈1是否为空:" << st.empty(1) << endl;
cout << "判断栈2是否为空:" << st.empty(2) << endl;
//栈1压栈3个元素
st.push(1, 10);
st.push(1, 20);
st.push(1, 30);
//栈2压栈3个元素
st.push(2, 100);
st.push(2, 200);
st.push(2, 300);
cout << "取栈1栈顶元素:" << st.getTop(1) << endl;
cout << "取栈2栈顶元素:" << st.getTop(2) << endl;
//栈1弹栈2个元素
st.pop(1);
st.pop(1);
//栈2弹栈2个元素
st.pop(2);
st.pop(2);
cout << "再取一次栈1栈顶元素:" << st.getTop(1) << endl;
cout << "再取一次栈2栈顶元素:" << st.getTop(2) << endl;
cout << "再次判断栈1是否为空:" << st.empty(1) << endl;
cout << "再次判断栈2是否为空:" << st.empty(2) << endl;
}