Skip to content

Instantly share code, notes, and snippets.

@itsmemattchung
Created June 19, 2016 17:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save itsmemattchung/bd3d135f024d1956a59e4d5654260915 to your computer and use it in GitHub Desktop.
Save itsmemattchung/bd3d135f024d1956a59e4d5654260915 to your computer and use it in GitHub Desktop.
Deque implementation
package dsandalgs;
public class Deque<E> {
int INIT_QUEUE_SIZE = 8;
int first = 0;
int size = 0;
E[] queue;
public Deque(){
this.queue = (E[]) new Object[this.INIT_QUEUE_SIZE];
}
public void addFirst(E item) throws IllegalStateException{
if (this.size == this.queue.length){
throw new IllegalStateException("Queue is full");
}
this.queue[first] = item;
this.first = (this.first + 1) % this.queue.length;
size++;
}
public E removeFirst(){
this.first = (this.first -1 + this.queue.length) % this.queue.length;
E item = this.queue[this.first];
return item;
}
public void addLast(E item){
int rear = (this.first - this.size + this.queue.length - 1) % this.queue.length;
this.queue[rear] = item;
this.size++;
}
@Override
public String toString(){
String myString = "";
for (int i=0; i< this.queue.length; i++){
myString = myString + " " + this.queue[i];
}
return myString;
}
public E removeLast(){
int rear = (this.first - this.size + this.queue.length) % this.queue.length;
E item = this.queue[rear];
this.queue[rear] = null;
this.size--;
return item;
}
public static void main(String[] args){
Deque<Integer> myDeque = new Deque<Integer>();
myDeque.addLast(5);
myDeque.addFirst(1);
myDeque.addFirst(2);
System.out.println(myDeque);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment