package com.hithomelabs.princeton1.module4;

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

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

    Node<E> start = null;
    Node<E> end = null;

    static private class Node<E>{
        E data;
        Node<E> next;

        private Node(E element){
            data=element;
            next=null;
        }
    }

    @Override
    public boolean isEmpty() {
        return start == null;
    }

    @Override
    public E dequeue() {
        if(isEmpty()) {
            return null;
        }
        E currentValue = start.data;
        start = start.next;
        return currentValue;
    }

    @Override
    public void enqueue(E element) {
        Node<E> new_node = new Node<E>(element);
        if(isEmpty())
            start = new_node;
        else
            end.next = new_node;
        end = new_node;
    }

    @Override
    public int size() {
        int size = 0;
        Node<E> sizePtr = start;
        while (sizePtr != null) {
            sizePtr = sizePtr.next;
            size++;
        }
        return size;
    }

    @Nonnull
    @Override
    public Iterator<E> iterator() {
        return new LinkedQueueIterator();
    }

    private class LinkedQueueIterator implements Iterator<E>{

        Node<E> traversePtr = start;

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

        @Override
        public E next() {
            E currentValue = traversePtr.data;
            traversePtr = traversePtr.next;
            return currentValue;
        }
    }
}
