Created
January 20, 2017 13:51
-
-
Save akaliacius/182ce67ffffa189ef52c6d1617e4fbe5 to your computer and use it in GitHub Desktop.
Implementation of Queue datastructure
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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