Skip to content

Instantly share code, notes, and snippets.

@cdduarte
Created June 5, 2014 04:04
Show Gist options
  • Save cdduarte/fad1e520ddf87bf8d5db to your computer and use it in GitHub Desktop.
Save cdduarte/fad1e520ddf87bf8d5db to your computer and use it in GitHub Desktop.
/**
* Queue<E> - circular array implementation of generic Queue<E> class;
* max #elements storeable is 1 less than the size of array,
* so we can distinguish between full and empty conditions.
*
* @author christopherduarte
* @reference robertirwin
* @course cis551
* @assignment Lab15
*
* @param <E>
*/
import java.util.Arrays;
import java.util.NoSuchElementException;
@SuppressWarnings("unchecked") // prevents warnings for casts in peek/pop methods
public class Queue<E> {
private int front; // one index counter-clockwise of first queue element
private int rear; // index of last queue element
private Object[] ra;
public Queue() {
this.ra = new Object[10+1];
this.front = 0;
this.rear = 0;
}
public Queue(int initialCapacity) throws IllegalArgumentException {
if ( initialCapacity < 1 )
throw new IllegalArgumentException();
// the +1 below makes up for not using one element of the object array
this.ra = new Object[initialCapacity+1];
this.front = 0;
this.rear = 0;
}
public void clear() {
this.front = 0;
this.rear = 0;
}
public boolean isEmpty() {
return this.front == this.rear;
}
public boolean add(E e) {
this.rear = (this.rear+1) % this.ra.length;
if ( this.rear == this.front ) {
Object[] tmp = Arrays.copyOf(ra, 2*this.ra.length);
tmp[this.rear] = e;
this.ra = tmp;
} else {
this.ra[this.rear] = e;}
return true;
}
public boolean offer(E e) {
this.rear = (this.rear+1) % this.ra.length;
if ( this.rear == this.front )
return false;
this.ra[this.rear] = e;
return true;
}
public E element() {
if ( this.isEmpty() )
throw new NoSuchElementException("tried to retrieve element from an empty queue");
return (E)this.ra[(this.front+1) % this.ra.length];
}
public E peek() {
if ( this.isEmpty() )
return null;
return (E)this.ra[(this.front+1) % this.ra.length];
}
public E peekLast() {
if ( this.isEmpty() )
return null;
return (E)this.ra[this.rear];
}
public E remove() {
if ( this.isEmpty() )
throw new NoSuchElementException("tried to remove element from an empty queue");
return (E)this.ra[this.front = (this.front+1) % this.ra.length];
}
public E poll() {
if ( this.isEmpty() )
return null;
return (E)this.ra[this.front = (this.front+1) % this.ra.length];
}
public int size() {
int d = this.rear - this.front;
return d >= 0 ? d
: this.ra.length - d;
}
public String toString() {
String s = "";
for ( int i = (this.front + 1) % this.ra.length; i != this.rear; i = (i+1) % this.ra.length )
s += String.format("%s%n", ((E)this.ra[i]).toString());
s += String.format("%s%n", ((E)this.ra[this.rear]).toString());
return s;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment