fork download
  1. class Main {
  2. public static void main (String[] args) {
  3. class Node<T> {
  4. T payload;
  5. Node<T> next;
  6. Node<T> prev;
  7. public Node(T payload) {
  8. this.payload = java.util.Objects.requireNonNull(payload);
  9. }
  10. }
  11. class Tunnel<T> {
  12. boolean hasExit;
  13. Node<T> head;
  14. Node<T> tail;
  15. public void add(T t) {
  16. Node<T> node = new Node<>(t);
  17. if (head == null) {
  18. head = node;
  19. } else {
  20. tail.next = node;
  21. node.prev = tail;
  22. }
  23. tail = node;
  24. }
  25. public T remove() {
  26. if (head == null) {
  27. return null;
  28. }
  29. if (hasExit) {
  30. Node<T> temp = head;
  31. if (head.next == null) {
  32. tail = null;
  33. } else {
  34. head.next.prev = null;
  35. }
  36. head = head.next;
  37. return temp.payload;
  38. } else {
  39. Node<T> temp = tail;
  40. if (head.next == null) {
  41. head = null;
  42. } else {
  43. tail.prev.next = null;
  44. }
  45. tail = tail.prev;
  46. return temp.payload;
  47. }
  48. }
  49. }
  50. Tunnel<String> t = new Tunnel<>();
  51. t.hasExit = true;
  52. t.add("Hugo");
  53. t.add("Paco");
  54. t.add("Luis");
  55. System.out.println(t.remove());
  56. System.out.println(t.remove());
  57. t.hasExit = false;
  58. System.out.println("¡Sin salida!");
  59. t.add("Juan");
  60. t.add("Olga");
  61. t.add("Ciro");
  62. for(String child; (child = t.remove()) != null;) {
  63. System.out.println(child);
  64. }
  65. }
  66. }
Success #stdin #stdout 0.1s 320320KB
stdin
Standard input is empty
stdout
Hugo
Paco
¡Sin salida!
Ciro
Olga
Juan
Luis