Skip to content

Instantly share code, notes, and snippets.

@kanrourou
Created January 11, 2014 07:15
Show Gist options
  • Save kanrourou/8368040 to your computer and use it in GitHub Desktop.
Save kanrourou/8368040 to your computer and use it in GitHub Desktop.
public class ResizingArrayQueueOfStrings{
private String[] s;
private int tail,head,size;
public ResizingArrayQueueOfStrings(){
tail=0;
head=0;
size=0;
s=new String[1];
}
public boolean isEmpty(){
return size==0;
}
public int sizeOfQueue(){
return size;
}
public int lengthOfArray(){
return s.length;
}
public void resize(int capacity){
String[] copy=new String[capacity];
for(int i=head,j=0;i<size+head;++i){
copy[j]=s[i%s.length];
j++;
}
head=0;
tail=size;
s=copy;
}
public void enqueue(String item){
if(size==s.length){
resize(2*s.length);
}
s[tail++]=item;
tail=tail%s.length;
size++;
}
public String dequeue(){
if(!isEmpty()){
String item=s[head];
s[head++]=null;
head=head%s.length;
size--;
if(size<=s.length/4){
resize(s.length/2);
}
return item;
}
else{
return "Queue is empty!";
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment