RosettaCodeData/Task/Queue-Definition/Java/queue-definition.java

41 lines
877 B
Java
Raw Normal View History

2013-04-10 23:57:08 -07:00
public class Queue<E>{
2014-01-17 05:32:22 +00:00
Node<E> head = null, tail = null;
2013-04-10 23:57:08 -07:00
2014-01-17 05:32:22 +00:00
static class Node<E>{
E value;
Node<E> next;
2013-04-10 23:57:08 -07:00
2014-01-17 05:32:22 +00:00
Node(E value, Node<E> next){
this.value= value;
this.next= next;
}
2013-04-10 23:57:08 -07:00
2014-01-17 05:32:22 +00:00
}
2013-04-10 23:57:08 -07:00
2014-01-17 05:32:22 +00:00
public Queue(){
}
2013-04-10 23:57:08 -07:00
2014-01-17 05:32:22 +00:00
public void enqueue(E value){ //standard queue name for "push"
Node<E> newNode= new Node<E>(value, null);
if(empty()){
head= newNode;
}else{
tail.next = newNode;
}
tail= newNode;
}
2013-04-10 23:57:08 -07:00
2014-01-17 05:32:22 +00:00
public E dequeue() throws java.util.NoSuchElementException{//standard queue name for "pop"
if(empty()){
throw new java.util.NoSuchElementException("No more elements.");
}
E retVal= head.value;
head= head.next;
return retVal;
}
2013-04-10 23:57:08 -07:00
2014-01-17 05:32:22 +00:00
public boolean empty(){
return head == null;
}
2013-04-10 23:57:08 -07:00
}