Suppose I have Push 5 elements In stack and after I pop out 4 elements.So My top will be on remaining 1 element of the stack . But When I called peek() after pop all elements except one which i push first , it showing stack is empty. Can U tell me where is my mistake why its showing stack is empty why its not displaying remaining one element of stack as top?
package stack;
public class StackUsingArray {
public int top;
protected int[] data;
protected static final int DEFAULT_CAPACITY = 10;
public StackUsingArray() throws Exception{
this(DEFAULT_CAPACITY);
}
public StackUsingArray(int capacity) throws Exception{
if(capacity<1) {
throw new Exception("Invalid Capacity");
}
this.data=new int[capacity];
this.top=-1;
}
public int size() {
return this.top+1;
}
public boolean isEmpty() {
return this.size()==0;
}
public void push(int value) throws Exception{
if(this.size()==data.length) {
throw new Exception("Stack Is Full");
}
this.top++;
this.data[this.top]=value;
}
public int pop() throws Exception{
if(this.size()==0) {
throw new Exception(“Stack Is Empty”);
}
int x= this.data[this.top];
this.data[this.top]=0;
this.top–;
return x;
}
public int peek() throws Exception{
if(this.size()==0) {
throw new Exception("Stack Is Empty");
}
int x= this.data[this.top];
return x;
}
public void display() {
for(int i = this.top;i>=0;i–){
System.out.print(data[i]+" ,");
}
System.out.println(" END");
}
}