在java解释中弹出堆栈[关闭]

问题描述 投票:-3回答:1

下面给出的代码是堆栈的实现。在它的pop函数中它不会返回顶部元素而不是顶部元素

      public class MyStack {
      private int maxSize;
      private long[] stackArray;
      private int top;

      public MyStack(int s) {
      maxSize = s;
      stackArray = new long[maxSize];
      top = -1;}
      public void push(long j) {
      stackArray[++top] = j;}

      public long pop() {
      return stackArray[top--];}

      public boolean isEmpty() {
      return (top == -1);}

      public boolean isFull() {
      return (top == maxSize - 1);}

      public static void main(String[] args) {
      MyStack theStack = new MyStack(10); 
      theStack.push(10);
      theStack.push(20);
      theStack.push(30);
      theStack.push(40);
      theStack.push(50);
      theStack.pop();

      while (!theStack.isEmpty()) {
      long value = theStack.pop();
      System.out.print(value);
      System.out.print(" ");}
      System.out.println("");}}
java stack pop
1个回答
1
投票

没有; top--的意思是:从顶部减去1,但这个表达式解析为top在递减之前所持有的。所以:

int x = 5; System.out.println(x--); System.out.println(x);将打印5然后4

您粘贴的代码使用top作为指示符指向最顶层的元素,这就是当堆栈为空时top为-1的原因。这有点不正统(它们都会有点清洁,top只会匹配堆栈的大小,如果你写的那样top指向第一个空闲位置),但这只是一个风格问题。

© www.soinside.com 2019 - 2024. All rights reserved.