LoganBlackisle

Opgave 2 - QueueList

Jan 8th, 2020
63
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.71 KB | None | 0 0
  1. package queueopgaver;
  2.  
  3. import java.util.NoSuchElementException;
  4.  
  5. /**
  6.  * An implementation of a queue as a list.
  7.  */
  8. public class QueueList implements QueueI {
  9.     private Node head;
  10.     private Node tail;
  11.  
  12.     /**
  13.      * Constructs an empty queue.
  14.      */
  15.     public QueueList() {
  16.         head = null;
  17.     }
  18.  
  19.     /**
  20.      * Checks whether this queue is empty.
  21.      *
  22.      * @return true if this queue is empty
  23.      */
  24.     @Override
  25.     public boolean isEmpty() {
  26.         return head == null;
  27.     }
  28.  
  29.     /**
  30.      * Adds an element to the tail of this queue.
  31.      *
  32.      * @param newElement the element to add
  33.      */
  34.     @Override
  35.     public void enqueue(Object newElement) {
  36.         Node newNode = new Node();
  37.         newNode.data = newElement;
  38.         if (head == null) {
  39.             head = newNode;
  40.             tail = newNode;
  41.         } else {
  42.             tail.next = newNode;
  43.             tail = newNode;
  44.         }
  45.     }
  46.  
  47.     /**
  48.      * Removes an element from the head of this queue.
  49.      *
  50.      * @return the removed element
  51.      */
  52.     @Override
  53.     public Object dequeue() { // TODO: SOMETHING IS WRONG WITH THIS METHOD!!!
  54.         if (head == null) {
  55.             throw new NoSuchElementException();
  56.         }
  57.         Object NewElement = head.data;
  58.         head = head.next;
  59.        
  60.         return NewElement;
  61.     }
  62.  
  63.     /**
  64.      * Returns the head of this queue. The queue is unchanged.
  65.      *
  66.      * @return the head element
  67.      */
  68.     @Override
  69.     public Object getFront() {
  70.         if (head == null) {
  71.             throw new NoSuchElementException();
  72.         }
  73.         return head.data;
  74.     }
  75.  
  76.     /**
  77.      * The number of elements on the queue.
  78.      *
  79.      * @return the number of elements in the queue
  80.      */
  81.     @Override
  82.     public int size() {
  83.         int count = 0;
  84.         Node temp = head;
  85.         while (temp != null) {
  86.             count++;
  87.             temp = temp.next;
  88.         }
  89.         return count;
  90.     }
  91.  
  92.     class Node {
  93.         public Object data;
  94.         public Node next;
  95.     }
  96. }
Add Comment
Please, Sign In to add comment