So I have written this JAVA-program for stack and the problem is I cant display the elements using the display() method which I used in the code.
here is my Stack class.
JavaScript
x
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]);
}
}
}
here is the main method class
JavaScript
public class Stackex {
public static void main(String[] args) {
Stack s = new Stack();
s.push(2);
s.push(4);
s.display();
}
}
when I try to execute what is get is “Stack underflow” from the isempty() and nothing is displayed after that. Please help me where I need to correct this code.
Advertisement
Answer
fix methods push
& display
:
JavaScript
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]);
}
}