java堆栈中的最大元素

uxh89sit  于 2021-07-09  发布在  Java
关注(0)|答案(1)|浏览(292)

关闭。这个问题需要细节或清晰。它目前不接受答案。
**想改进这个问题吗?**通过编辑这个帖子来添加细节并澄清问题。

四年前关门了。
改进这个问题
https://www.hackerrank.com/challenges/maximum-element
ques将执行三个查询1-用于将elment添加到堆栈2-用于弹出元素3-用于打印max元素链接张贴在hackerrank上的iam无法获得6-7个案例的输出

int n,i;int in1,in2;
    Scanner sc=new Scanner(System.in);
    n=sc.nextInt();
    Stack<Integer> st=new Stack<Integer>();//stack for elements
    Stack<Integer> stmax=new Stack<Integer>(); // stack for storing maximum
        for(i=1;i<=n;i++)
        {
        in1=sc.nextInt();
        if(in1==1)
            {
                     in2=sc.nextInt();
                     if(st.size()==0)
                       {

                              stmax.push(in2);
                              st.push(in2);
                       }
                     else
                         {
                              if(in2>=stmax.peek())
                                  {

                              stmax.push(in2);
                              }
                               st.push(in2);

                          }    
        }
        if(in1==2)
            {
            if(st.peek()==stmax.peek())
                stmax.pop();
            st.pop();

        }
        if(in1==3)
            {
            System.out.println(stmax.peek());
        }

        }
qpgpyjmq

qpgpyjmq1#

您的代码是正确的,但是 if(st.peek()==stmax.peek()) 使用 if(st.peek().equals(stmax.peek())) 这将使您的代码通过所有测试用例

相关问题