Skip to content

Instantly share code, notes, and snippets.

@akaliacius
Created January 20, 2017 13:51
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 akaliacius/182ce67ffffa189ef52c6d1617e4fbe5 to your computer and use it in GitHub Desktop.
Save akaliacius/182ce67ffffa189ef52c6d1617e4fbe5 to your computer and use it in GitHub Desktop.
Implementation of Queue datastructure
import java.util.NoSuchElementException;
public class LinkedQueue<E> {
private Node<E> first, last;
private class Node<E>{
E content;
Node<E> next = null;
}
public boolean isEmpty(){
return first == null;
}
public void enqueue(E content){
Node<E> newNode = new Node<>();
newNode.content = content;
if(isEmpty()){
first = newNode;
last = newNode;
}
else{
last.next = newNode;
last = newNode;
}
}
public E dequeue(){
if(isEmpty())throw new NoSuchElementException("The queue is empty");
else{
Node<E> oldFirst = first;
E content = first.content;
first = first.next;
if(isEmpty())last = null;
else oldFirst.next = null;
return content;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment