不显示堆栈中的元素

问题描述

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

这是我的Stack类。

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() 中的“堆栈下溢” 时,此后什么也没有显示。请在需要纠正此代码的地方帮助我。

解决方法

只有在git config credential.helper store返回push时,您对isempty的呼叫才会推送。

因此,第一次推送成功,并将top设置为0。

第二次推送永远不会发生,因为true返回false。

因此,当您转到isempty时,display循环将永远不会重复,因为for为0。

,

修复方法pushdisplay

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

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

首先要解决一些编译错误。 在方法display中,i并未声明,请像这样修复它:

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;
    }
}

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