题目描述
已知顺序栈类的定义、构造函数及主函数的代码如下,请完成类的其它成员函数,完成相应的输出。
const int StackSize=5; //顺序栈的最大长度(请勿改动)
template
class SeqStack
{
public:
SeqStack( ) ; //构造函数,栈的初始化
~SeqStack( ); //析构函数
void Push(T x); //将元素x入栈
T Pop( ); //将栈顶元素弹出
T GetTop( ); //取栈顶元素(并不删除)
bool Empty( ); //判断栈是否为空
private:
T data[StackSize]; //存放栈元素的数组
int top; //栈顶指针,指示栈顶元素在数组中的下标
};
/
前置条件:栈不存在
输 入:无
功 能:栈的初始化
输 出:无
后置条件:构造一个空栈
/
template
SeqStack
{
top=-1;
}
/
前置条件:栈已存在
输 入:无
功 能:销毁栈
输 出:无
后置条件:释放栈所占用的存储空间
/
template
SeqStack
{
}
int main()
{
SeqStack
int x;
while(1)
{
cin>>x;
if(!x) break;
try{
s.Push(x);
}
catch(const char ms){
cout<<”Push:”<
}
cout<<”Gettop:”<
while(!s.Empty())
{
cout<
cout<
cout<<”Gettop:”<
catch(const char
cout<<”Gettop:”<
return 0;
}
输入
输出
样例输入
样例输出
Push:Overflow
Push:Overflow
Gettop:5
5 4 3 2 1
Gettop:Downflow
提示
来源
提交
import java.util.Scanner;class SeqStack{int stackMax = 5;Object[] data;int top = 0;public SeqStack() {data = new Object[stackMax];top = 0;}public void push(Object x) throws Exception {if(top==stackMax){throw new Exception("Overflow");}else{data[top++] = x;}}public Object pop() throws Exception {if(top==0){throw new Exception("Downflow");}else {return data[--top];}}public Object getTop() throws Exception {if(top==0){throw new Exception("Downflow");}else {return data[top - 1];}}public boolean isEmpty(){return top==0;}}public class Main {public static void main(String[] args) {SeqStack s = new SeqStack();Scanner scanner = new Scanner(System.in);while(scanner.hasNext()){Object data = scanner.nextInt();if((int)data == 0){break;}try {s.push(data);} catch (Exception e) {System.out.println("Push:"+e.getMessage());}}try {System.out.println("Gettop:"+s.getTop());} catch (Exception e) {System.out.println("Gettop:"+e.getMessage());}while (!s.isEmpty()){try {System.out.print(s.pop() + " ");} catch (Exception e) {System.out.println("Pop:"+e.getMessage());}}System.out.println();try {System.out.println(s.getTop());} catch (Exception e) {System.out.println("Gettop:"+e.getMessage());}}}
