您的位置:首页 > 理论基础 > 数据结构算法

两栈共享空间

2013-07-13 18:27 232 查看
#include <iostream>
using namespace std;

const int StackSize = 100;

template <class DataType>
class BothStack
{

private:
int data[StackSize];  ///存放两个栈的数组
int top1, top2; ///两个栈的栈顶指针,分别为各自栈顶元素在数组中的下标

public:
BothStack() {
top1 = -1;
top2 = StackSize;
}  ///构造函数,将两个栈分别初始化
~BothStack() {} ///析构函数为空
void Push(int i, DataType x); ///入栈操作,将元素x压入栈i
int Pop(int i);  ///出栈操作,对栈i执行出栈操作
int GetTop(int i) {
if (top1 != -1 && top2 != StackSize)
return data[top];
}  ///取栈i的栈顶元素(并不删除)
int Empty(int i) {
if (top1 == -1 && top2 == StackSize)
return 1;
else
return 0;
}  ///判断栈是否为空

};

template <class DataType>
void BothStack<DataType>::Push(int i, DataType x) ///入栈操作,将元素x入栈
{
if (top1 == top2 - 1)  throw "上溢"; ///判断是否栈满
if (i == 1)  data[++top1] = x; ///在栈1中插入
if (i == 2)  data[--top2] = x; ///在栈2中插入
}

template <class DataType>
int BothStack<DataType>::Pop(int i)  ///出栈操作,将栈顶元素弹出
{
if (i == 1) { ///在栈1中删除
if (top1 == -1) ///判断栈1是否为空
throw "下溢";
return data[top1 + +];
}
if (i == 2) { ///在栈2中删除
if (top2 == StackSize) ///判断栈2是否为空
throw "下溢";
return data[--top2];
}
}

int main()
{

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  数据结构