class Main {
	public static void main (String[] args) {
        class Node<T> {
            T payload;
            Node<T> next;
            Node<T> prev;
            public Node(T payload) {
                this.payload = java.util.Objects.requireNonNull(payload);
            }
        }
        class Tunnel<T> {
            boolean hasExit;
            Node<T> head;
            Node<T> tail;
            public void add(T t) {
                Node<T> node = new Node<>(t);
                if (head == null) {
                    head = node;
                } else {
                    tail.next = node;
                    node.prev = tail;
                }
                tail = node;
            }
            public T remove() {
                if (head == null) {
                    return null;
                }
                if (hasExit) {
                    Node<T> temp = head;
                    if (head.next == null) {
                        tail = null;
                    } else {
                        head.next.prev = null;
                    }
                    head = head.next;
                    return temp.payload;
                } else {
                    Node<T> temp = tail;
                    if (head.next == null) {
                        head = null;
                    } else {
                        tail.prev.next = null;
                    }
                    tail = tail.prev;
                    return temp.payload;
                }
            }
        }
        Tunnel<String> t = new Tunnel<>();
        t.hasExit = true;
        t.add("Hugo");
        t.add("Paco");
        t.add("Luis");
        System.out.println(t.remove());
        System.out.println(t.remove());
        t.hasExit = false;
        System.out.println("¡Sin salida!");
        t.add("Juan");
        t.add("Olga");
        t.add("Ciro");
        for(String child; (child = t.remove()) != null;) {
            System.out.println(child);
        }
	}
}