import java.util.Iterator;

public class LinkedQueue<E> implements Queue<E>,Iterable<E>{

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

        public Node(E value, Node<E> next) {
            this.value = value;
            this.next = next;
        }
    }
    private Node head=new Node<>(null,null);
    private Node tail=head;
    private int size=0;
    private int capacity=Integer.MAX_VALUE;
    {
        tail.next=head;
    }
    public LinkedQueue(int capacity) {
        this.capacity = capacity;
    }

    public LinkedQueue() {
    }

    @Override
    public boolean offer(E value) {
        if(isFull()){
            return false;
        }
        Node node=new Node<>(value,tail.next);
        tail.next=node;
        tail=node;
        size++;
        return true;
    }

    @Override
    public E poll() {
        if(isEmpty()){
            return null;
        }
        E remove= (E) head.next.value;
        head.next=head.next.next;
        size--;
        return remove;
    }

    @Override
    public E peek() {
        if(isEmpty()){
            return null;
        }
        return (E) head.next.value;
    }

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

    @Override
    public boolean isFull() {
        return size==capacity;
    }

    @Override
    public Iterator<E> iterator() {
        return new Iterator<E>() {
            Node<E> p=head.next;
            @Override
            public boolean hasNext() {
                return p!=head;
            }

            @Override
            public E next() {
                E v=p.value;
                p=p.next;
                return v;
            }
        };
    }
}

Logo

有“AI”的1024 = 2048,欢迎大家加入2048 AI社区

更多推荐