1012: 顺序栈
Description
已知顺序栈类的定义、构造函数及主函数的代码如下,请完成类的其它成员函数,完成相应的输出。
const int StackSize=5; //顺序栈的最大长度(请勿改动)
template <class T> //定义模板类SeqStack
class SeqStack
{
public:
SeqStack( ) ; //构造函数,栈的初始化
~SeqStack( ); //析构函数
void Push(T x); //将元素x入栈
T Pop( ); //将栈顶元素弹出
T GetTop( ); //取栈顶元素(并不删除)
bool Empty( ); //判断栈是否为空
private:
T data[StackSize]; //存放栈元素的数组
int top; //栈顶指针,指示栈顶元素在数组中的下标
};
/*
* 前置条件:栈不存在
* 输 入:无
* 功 能:栈的初始化
* 输 出:无
* 后置条件:构造一个空栈
*/
template <class T>
SeqStack<T>::SeqStack( )
{
top=-1;
}
/*
* 前置条件:栈已存在
* 输 入:无
* 功 能:销毁栈
* 输 出:无
* 后置条件:释放栈所占用的存储空间
*/
template <class T>
SeqStack<T>::~SeqStack( )
{
}
int main()
{
SeqStack<int> s;
int x;
while(1)
{
cin>>x;
if(!x) break;
try{
s.Push(x);
}
catch(const char *ms){
cout<<"Push:"<<ms<<endl;
}
}
cout<<"Gettop:"<<s.GetTop()<<endl;
while(!s.Empty())
{
cout<<s.Pop()<<" ";
}
cout<<endl;
try{
cout<<"Gettop:"<<s.GetTop()<<endl;
}
catch(const char *ms){
cout<<"Gettop:"<<ms<<endl;
}
return 0;
}
Input
Output
Sample Input
1 2 3 4 5 6 7 0
Sample Output
Push:Overflow
Push:Overflow
Gettop:5
5 4 3 2 1
Gettop:Downflow
#include <iostream>
using namespace std;
const int StackSize = 5; //顺序栈的最大长度(请勿改动)
template<class T> //定义模板类SeqStack
class SeqStack {
public:
SeqStack(); //构造函数,栈的初始化
~SeqStack(); //析构函数
void Push(T x); //将元素x入栈
T Pop(); //将栈顶元素弹出
T GetTop(); //取栈顶元素(并不删除)
bool Empty(); //判断栈是否为空
private:
T data[StackSize]; //存放栈元素的数组
int top; //栈顶指针,指示栈顶元素在数组中的下标
};
template<class T>
SeqStack<T>::SeqStack() {
top = -1;
}
template<class T>
SeqStack<T>::~SeqStack() {
}
template<class T>
void SeqStack<T>::Push(T x) {
if (top >= StackSize - 1)
throw "Overflow";
data[++top] = x;
}
template<class T>
T SeqStack<T>::Pop() {
if (top == -1) throw "Downflow";
return data[top--];
}
template<class T>
T SeqStack<T>::GetTop() {
if(top == -1)throw "Downflow";
return data[top];
}
template<class T>
bool SeqStack<T>::Empty() {
return top == -1;
}
int main() {
SeqStack<int> s;
int x;
while (1) {
cin >> x;
if (!x) break;
try {
s.Push(x);
}
catch (const char *ms) {
cout << "Push:" << ms << endl;
}
}
cout << "Gettop:" << s.GetTop() << endl;
while (!s.Empty()) {
cout << s.Pop() << " ";
}
cout << endl;
try {
cout << "Gettop:" << s.GetTop() << endl;
}
catch (const char *ms) {
cout << "Gettop:" << ms << endl;
}
return 0;
}