题目描述

已知顺序栈类的定义、构造函数及主函数的代码如下,请完成类的其它成员函数,完成相应的输出。
const int StackSize=5; //顺序栈的最大长度(请勿改动)
template //定义模板类SeqStack
class SeqStack
{
public:
SeqStack( ) ; //构造函数,栈的初始化
~SeqStack( ); //析构函数
void Push(T x); //将元素x入栈
T Pop( ); //将栈顶元素弹出
T GetTop( ); //取栈顶元素(并不删除)
bool Empty( ); //判断栈是否为空
private:
T data[StackSize]; //存放栈元素的数组
int top; //栈顶指针,指示栈顶元素在数组中的下标
};

/
前置条件:栈不存在
输 入:无
功 能:栈的初始化
输 出:无
后置条件:构造一个空栈
/

template
SeqStack::SeqStack( )
{
top=-1;
}

/

前置条件:栈已存在
输 入:无
功 能:销毁栈
输 出:无
后置条件:释放栈所占用的存储空间
/

template
SeqStack::~SeqStack( )
{
}
int main()
{
SeqStack s;
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< try{
cout<<”Gettop:”< }
catch(const char
ms){
cout<<”Gettop:”< }
return 0;
}

输入

输出

样例输入

1 2 3 4 5 6 7 0

样例输出

Push:Overflow
Push:Overflow
Gettop:5
5 4 3 2 1
Gettop:Downflow

提示

来源

提交

  1. import java.util.Scanner;
  2. class SeqStack{
  3. int stackMax = 5;
  4. Object[] data;
  5. int top = 0;
  6. public SeqStack() {
  7. data = new Object[stackMax];
  8. top = 0;
  9. }
  10. public void push(Object x) throws Exception {
  11. if(top==stackMax){
  12. throw new Exception("Overflow");
  13. }else{
  14. data[top++] = x;
  15. }
  16. }
  17. public Object pop() throws Exception {
  18. if(top==0){
  19. throw new Exception("Downflow");
  20. }else {
  21. return data[--top];
  22. }
  23. }
  24. public Object getTop() throws Exception {
  25. if(top==0){
  26. throw new Exception("Downflow");
  27. }else {
  28. return data[top - 1];
  29. }
  30. }
  31. public boolean isEmpty(){
  32. return top==0;
  33. }
  34. }
  35. public class Main {
  36. public static void main(String[] args) {
  37. SeqStack s = new SeqStack();
  38. Scanner scanner = new Scanner(System.in);
  39. while(scanner.hasNext()){
  40. Object data = scanner.nextInt();
  41. if((int)data == 0){
  42. break;
  43. }
  44. try {
  45. s.push(data);
  46. } catch (Exception e) {
  47. System.out.println("Push:"+e.getMessage());
  48. }
  49. }
  50. try {
  51. System.out.println("Gettop:"+s.getTop());
  52. } catch (Exception e) {
  53. System.out.println("Gettop:"+e.getMessage());
  54. }
  55. while (!s.isEmpty()){
  56. try {
  57. System.out.print(s.pop() + " ");
  58. } catch (Exception e) {
  59. System.out.println("Pop:"+e.getMessage());
  60. }
  61. }
  62. System.out.println();
  63. try {
  64. System.out.println(s.getTop());
  65. } catch (Exception e) {
  66. System.out.println("Gettop:"+e.getMessage());
  67. }
  68. }
  69. }