fork download
  1. import java.util.*;
  2. import java.lang.*;
  3. import java.io.*;
  4.  
  5. class GenericQueue<Item> implements Iterable<Item> {
  6. private Node first, last;
  7.  
  8. private class Node {
  9. Item item;
  10. Node next;
  11. }
  12.  
  13. public boolean isEmpty() {
  14. return first == null;
  15. }
  16.  
  17. public void enqueue(Item item) {
  18. Node oldLast = last;
  19. last = new Node();
  20. last.item = item;
  21. last.next = null;
  22. if (isEmpty()) first = last;
  23. else oldLast.next = last;
  24. }
  25.  
  26. public Item dequeue() {
  27. Item item = first.item;
  28. first = first.next;
  29. if (isEmpty()) last = null;
  30. return item;
  31. }
  32.  
  33. @Override
  34. public Iterator<Item> iterator() {
  35. return new LinkedIterator();
  36. }
  37.  
  38. private class LinkedIterator implements Iterator<Item> {
  39. private Node current = first;
  40.  
  41. public boolean hasNext() {
  42. return current != null;
  43. }
  44.  
  45. public Item next() {
  46. if (!hasNext()) throw new NoSuchElementException();
  47. Item item = current.item;
  48. current = current.next;
  49. return item;
  50. }
  51. }
  52. }
  53.  
  54. public class Main {
  55. public static void main(String[] args) throws java.lang.Exception {
  56. GenericQueue<String> strQ = new GenericQueue<>();
  57. strQ.enqueue("Cat");
  58. strQ.enqueue("Dog");
  59.  
  60. System.out.println("Iterating:");
  61. for (String s : strQ) System.out.println(s);
  62.  
  63. System.out.println("Dequeuing:");
  64. System.out.println(strQ.dequeue());
  65. System.out.println(strQ.dequeue());
  66. }
  67. }
  68.  
Success #stdin #stdout 0.09s 54440KB
stdin
Standard input is empty
stdout
Iterating:
Cat
Dog
Dequeuing:
Cat
Dog