首页 > 解决方案 > 不显示堆栈中的元素

问题描述

所以我已经为堆栈编写了这个 JAVA 程序,问题是我无法使用我在代码中使用的 display() 方法显示元素。

这是我的堆栈类。

public class Stack {
//members
private int top;
private int size;
private int[] a;
private int i;

//constructor
public Stack() {
    this.top = -1;
    this.size = 5;
    this.a = new int[size];
}

private boolean isempty() {
    if(top == -1) {
        System.out.println("Stack Underflow");
        return true;
    }
    return false;
}

private boolean isfull() {
    if(top == size-1) {
        System.out.println("Stack Overflow");
        return true;
    }
    return false;
}

public void push(int n) {
if(isempty()) {
    top+=1;
    a[top] = n;
    }
}

public void pop() {
    if(isfull()) {
        System.out.println("popped : "+ a[top]);
        top-=1;         
    }
}

public void display() {
    for(i=0;i<top;i++) {
        System.out.println(a[i]);
    }

}
}

这是主要的方法类

public class Stackex {
public static void main(String[] args) {
    Stack s = new Stack();
    s.push(2);
    s.push(4);
    s.display();
}

}

当我尝试执行时,从isempty()得到的是“堆栈下溢” ,之后什么都没有显示。请在我需要更正此代码的地方帮助我。

标签: javastack

解决方案


首先要修复一些编译错误。在未声明的方法中,像这样修复它displayi

public void display() {
    for (int i = 0; i < top; i++) { // add int i = 0
        System.out.println(a[i]);
    }
}

比改变这个:

private int[] a;;
private int ijk]kkkk 

对此:

private int[] a;

现在你的问题是因为isempty返回 false。所以改变 push 方法是这样的:

public void push(int n) {
    if (!isfull()) {
        top += 1;
        a[top] = n;
    }
}

添加元素时,您要检查堆栈是否未满。


推荐阅读