Created
August 19, 2017 22:15
-
-
Save mohnoor94/2016d4259de21b5a7aa244917cb953a2 to your computer and use it in GitHub Desktop.
Simple Java Implementation of Stack
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // 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