package com.hithomelabs.princeton1.module4;

import javax.annotation.Nonnull;
import java.util.Iterator;

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

    Node head;
    Node tail;
    int size;

    private class Node{
        E value;
        Node next;

        Node(E value){
            this.value = value;
        }
    }

    @Override
    public boolean isEmpty() {
        return size==0;
    }

    @Override
    public E dequeue() {
        if(isEmpty())
            return null;
        E element = head.value;
        // Only a single element is present
        if (head == tail){
            tail = null;
        }
        head = head.next;
        --size;
        return element;
    }

    @Override
    public void enqueue(E element) {
        Node newNode = new Node(element);
        if(isEmpty())
            head = newNode;
        else
            tail.next = newNode;
        tail = newNode;
        ++size;
    }

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

    @Override
    @Nonnull
    public Iterator<E> iterator() {
        return new Iterator<E>() {
            Node current = head;
            @Override
            public boolean hasNext() {
                return current != null;
            }

            @Override
            public E next() {
                E element = current.value;
                current = current.next;
                return element;
            }
        };
    }
}
