Created
August 19, 2017 22:17
-
-
Save mohnoor94/bae4d17887a4020e52b41c68961f05d7 to your computer and use it in GitHub Desktop.
Simple Java Implementation of Queue
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 ArrayQueue { | |
| private final int[] queue; | |
| private int first = 0; | |
| private int last = 0; | |
| int size = 0; | |
| public ArrayQueue(int size) { | |
| queue = new int[size]; | |
| } | |
| boolean isEmpty() { // check if the queue is empty! | |
| return size == 0; | |
| } | |
| boolean isFull() { // check if the queue is full! | |
| return size == queue.length; | |
| } | |
| boolean isExist(int x) { // check if a certain item is exist in the queue! | |
| for (int i = 0; i < size; i++) { | |
| if (queue[i] == x) { | |
| return true; | |
| } | |
| } | |
| return false; | |
| } | |
| public void addLast(int x) { // enqueue | |
| if (isFull()) { | |
| throw new RuntimeException("the queue is full"); | |
| } | |
| queue[last] = x; | |
| size++; | |
| last = (last + 1) % queue.length; | |
| } | |
| public int removeFirst() { // dequeue | |
| if (isEmpty()) { | |
| throw new RuntimeException("the queue is empty"); | |
| } | |
| int r = queue[first]; | |
| first = (first + 1) % queue.length; | |
| size--; | |
| return r; | |
| } | |
| public int get(int index) { // get first item without removing it (peek) | |
| return queue[index]; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment