Guest User

Untitled

a guest
Jan 20th, 2019
79
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.14 KB | None | 0 0
  1. /*
  2. * To change this template, choose Tools | Templates
  3. * and open the template in the editor.
  4. */
  5. package randomid;
  6. import java.util.NoSuchElementException;
  7.  
  8. /** Queue data structure */
  9. public class ListQueue<T> {
  10.  
  11. /** Queue node data structure */
  12. private class Node<T> {
  13. Node<T> next;
  14. T element;
  15.  
  16. public Node( T element,Node<T> next ) {
  17. this.element = element;
  18. this.next = next;
  19. }
  20. }
  21.  
  22. /** Head of the queue */
  23. private Node<T> head = null;
  24. /** Tail of the queue */
  25. private Node<T> tail = null;
  26.  
  27. /** Enqueue a new node at the tail (end) of the queue */
  28. public void enqueue( T t ) {
  29. Node<T> newNode = new Node<>( t, null );
  30. if( isEmpty( ) ) {
  31. head = tail = newNode;
  32. } else {
  33. tail.next = newNode;
  34. tail = newNode;
  35. }
  36. }
  37.  
  38. /** Dequeue the node from the head (top) of the queue */
  39. public T dequeue( ) throws NoSuchElementException {
  40. if( isEmpty( ) ) {
  41. throw new NoSuchElementException( );
  42. }
  43.  
  44. T element = head.element;
  45. head = head.next;
  46. return element;
  47. }
  48.  
  49. /** Checks if the queue is empty */
  50. public boolean isEmpty( ) {
  51. return head == null;
  52. }
  53.  
  54.  
  55. }
Add Comment
Please, Sign In to add comment