Skip to content

Instantly share code, notes, and snippets.

@skmangalam
Created December 19, 2017 18:29
Show Gist options
  • Select an option

  • Save skmangalam/9e61cdda562ff08d40e94d8df7de7781 to your computer and use it in GitHub Desktop.

Select an option

Save skmangalam/9e61cdda562ff08d40e94d8df7de7781 to your computer and use it in GitHub Desktop.
Implementation Of Queue Using an Array
public class ArrayQueue<X> {
private X[] data;
private int front;
private int end;
public ArrayQueue() {
front = -1;
end = -1;
data = (X[])new Object[1000];
}
public int size() {
//if the queue is empty, we return 0
if(front == -1 && end == -1) {
return 0;
}
else {
return end - front + 1;
}
}
public void enQueue(X item) {
//if the queue is full
if((end + 1) % data.length == front) {
throw new IllegalStateException("The Queue is full!");
}
//otherwise check to see if any items have been added to the queue yet
else if(size() == 0) {
front++;
end++;
data[end] = item;
}
//otherwise add the item to the end of the queue
else {
end++;
data[end] = item;
}
}
public X deQueue() {
X item = null;
//if the queue is empty we can't dequeue anything
if(size() == 0) {
throw new IllegalStateException("Can't dequeue because the queue is empty!");
}
//otherwise if this is the last item on the queue, the queue needs to get reset to empty
else if(front == end) {
item = data[front];
data[front] = null;
front = -1;
end = -1;
}
//otherwise grab the front of the queue, return it and adjust the front pointer
else {
item = data[front];
data[front] = null;
front++;
}
return item;
}
public boolean hasObject(X item) {
boolean found = false;
// if the queue is empty just immediately return false
if(size() == 0) {
return found;
}
for(int i = front; i < end; i++) {
if(data[i].equals(item)) {
found = true;
break;
}
}
return found;
}
public X getObjectAtIndex(int position) {
if(size() == 0 || position > size()) {
throw new IllegalArgumentException("No items in the queue or the position is greater than the queue size");
}
int Index = 0;
for(int i = front; i < end; i++) {
if(Index == position) {
return data[i];
}
Index++;
}
//if we didn't find the item in the stack throw an exception
throw new IllegalArgumentException("Could not get item at position: " + position);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment