Skip to content

Instantly share code, notes, and snippets.

@mohnoor94
Created August 19, 2017 22:15
Show Gist options
  • Select an option

  • Save mohnoor94/2016d4259de21b5a7aa244917cb953a2 to your computer and use it in GitHub Desktop.

Select an option

Save mohnoor94/2016d4259de21b5a7aa244917cb953a2 to your computer and use it in GitHub Desktop.
Simple Java Implementation of Stack
// www.abukhleif.com
class ArrayStack {
private final int[] stack;
private final int size;
private int top;
public ArrayStack(int size) {
this.size = size;
stack = new int[size];
}
boolean isEmpty() { // check if the stack is empty
return top == 0;
}
boolean isFull() { // check if the stack is full
return top == size;
}
void push(int x) { // add an item to the top of the stack
if (!isFull()) {
stack[top++] = x;
} else {
throw new RuntimeException("The stack is full");
}
}
int pop() { // get the top item of the stack, then remove it
if (!isEmpty()) {
return stack[--top];
} else {
throw new RuntimeException("The stack is empty");
}
}
int top() { // get the top item of the stack
if (!isEmpty()) {
return stack[top];
} else {
throw new RuntimeException("The stack is empty");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment