2016-06-24

Queue(FIFO) implementation using Java



A queue is a collection that is based on the first-in-first-out (FIFO) policy.

  • dequeue() - get an item from the queue.
  • enqueue() - insert item into the queue.


  1. public class Queue<Item> implements Iterable<Item>
  2. {
  3. private Node first; // link to least recently added node
  4. private Node last; // link to most recently added node
  5. private int N; // number of items on the queue
  6. private class Node
  7. { // nested class to define nodes
  8. Item item;
  9. Node next;
  10. }
  11. public boolean isEmpty() { return first == null; } // Or: N == 0.
  12. public int size() { return N; }
  13. public void enqueue(Item item)
  14. { // Add item to the end of the list.
  15. Node oldlast = last;
  16. last = new Node();
  17. last.item = item;
  18. last.next = null;
  19. if (isEmpty()) first = last;
  20. else oldlast.next = last;
  21. N++;
  22. }
  23. public Item dequeue()
  24. { // Remove item from the beginning of the list.
  25. Item item = first.item;
  26. first = first.next;
  27. if (isEmpty()) last = null;
  28. N--;
  29. return item;
  30. }
  31. }

No comments:

Post a Comment