Skip to content

Instantly share code, notes, and snippets.

@devsingh1234
Created February 17, 2022 15:18
Show Gist options
  • Save devsingh1234/8d123af61236d493c479b0ca956149f6 to your computer and use it in GitHub Desktop.
Save devsingh1234/8d123af61236d493c479b0ca956149f6 to your computer and use it in GitHub Desktop.
package stack;
public class StackUsingArray {
private int[] data;
private int top;
public 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()==this.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("the stack is already empty");
}
int rv = this.data[this.top];
this.data[this.top] = 0;
this.top--;
return rv;
}
public int top() throws Exception{
if(this.size() == 0 ){
throw new Exception("the stack is already empty");
}
int rv = this.data[this.top];
return rv;
}
public void display(){
for (int i = this.top; i >=0 ; i--){
System.out.println(this.data[i]+",");
}
System.out.println();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment