import java.util.AbstractQueue;
import java.util.Iterator;
import java.util.NoSuchElementException;

public class LinkedQueue<E> extends AbstractQueue<E> {

    private Node<E> head; // Tête de la file
    private Node<E> tail; // Fin de la file
    private int size;     // Taille de la file

    public LinkedQueue() {
        head = null;
        tail = null;
        size = 0;
    }

    @Override
    public boolean offer(E e) {
        if (e == null) {
            throw new NullPointerException("Les éléments null ne sont pas autorisés.");
        }
        Node<E> newNode = new Node<>(e);
        if (tail == null) { // File vide
            head = newNode;
            tail = newNode;
        } else {
            tail.next = newNode;
            tail = newNode;
        }
        size++;
        return true;
    }

    @Override
    public E poll() {
        if (head == null) { // File vide
            return null;
        }
        E element = head.element;
        head = head.next;
        if (head == null) { // La file est maintenant vide
            tail = null;
        }
        size--;
        return element;
    }

    @Override
    public E peek() {
        return (head == null) ? null : head.element;
    }

    @Override
    public Iterator<E> iterator() {
        return new Iterator<E>() {
            private Node<E> current = head;

            @Override
            public boolean hasNext() {
                return current != null;
            }

            @Override
            public E next() {
                if (current == null) {
                    throw new NoSuchElementException();
                }
                E element = current.element;
                current = current.next;
                return element;
            }
        };
    }

    @Override
    public int size() {
        return size;
    }
}
