图片讲解
代码实现
#define _CRT_SECURE_NO_WARNINGS 1
#include<iostream>
using namespace std;
#include <assert.h>
const int SizeStack = 20;
template<class T>
class BothStack
{
public:
BothStack() :count1(0), count2(0)
{
top1 = -1;
top2 = SizeStack;
}
~BothStack()
{}
void Push(int i, T x);
void Pop(int i);
T GetTop(int i);
bool Empty(int i);
void Print(int i);
T Size(int i);
protected:
T data[SizeStack];
int top1, top2;
int count1, count2;
};
template<class T>
void BothStack<T>::Push(int i, T x)
{
if (top1 == top2 - 1)
{
throw "上溢";
}
if (i == 1)
{
data[++top1] = x;
++count1;
}
else
{
data[--top2] = x;
++count2;
}
}
template<class T>
void BothStack<T>::Pop(int i)
{
if (i == 1)
{
if (top1 == -1)
{
throw "下溢";
}
top1 =--top1;
--count1;
}
else
{
if (top2 == SizeStack)
{
throw "下溢";
}
top2 = ++top2;
--count2;
}
}
template<class T>
T BothStack<T>::GetTop(int i)
{
if (i == 1)
{
if (top1 != -1)
{
return data[top1];
}
}
else
{
if (top2 != SizeStack)
{
return data[top2];
}
}
return -1;
}
template<class T>
T BothStack<T>::Size(int i)
{
if (i == 1)
{
return count1;
}
else
{
return count2;
}
}
template<class T>
bool BothStack<T>::Empty(int i)
{
if (i == 1)
{
if (top1 == -1)
{
return true;
}
else
{
return false;
}
}
else
{
if (top2 == SizeStack)
{
return true;
}
else
{
return false;
}
}
}
template <class T>
void BothStack<T>::Print(int i)
{
if (i == 1)
{
assert(top1 != -1);
int temp1 = top1;
for (int i = 0; i < count1; ++i)
{
cout << data[temp1--]<<" ";
}
cout << endl;
}
else
{
assert(top2 != -1);
int temp2 = top2;
for (int i = 0; i < count2; ++i)
{
cout << data[temp2++] << " ";
}
cout << endl;
}
}
void TestFun()
{
BothStack<int> bs;
bs.Push(1, 1);
bs.Push(1, 2);
bs.Push(1, 3);
bs.Push(1, 4);
bs.Push(1, 5);
bs.Push(2, 6);
bs.Push(2, 7);
bs.Push(2, 8);
bs.Push(2, 9);
bs.Push(2, 10);
bs.Push(2, 20);
bs.Push(2, 30);
cout << "栈1: ";
bs.Print(1);
cout << "栈2: ";
bs.Print(2);
cout <<"栈1有效元素:"<<bs.Size(1)<<" "<< "栈1顶元素:" << bs.GetTop(1) << endl;
cout << "栈2有效元素:" << bs.Size(2)<<" " << "栈2顶元素:" << bs.GetTop(2) << endl;
bs.Pop(1);
bs.Print(1);
bs.Pop(2);
bs.Print(2);
}
int main()
{
TestFun();
system("pause");
return 0;
}
实现结果