This is my Queue implementation in Java. Would appreciate a review of the code.

import java.util.Iterator;

public class Queue<T>implements Iterable<T> {

    private Node first, last;
    private int size;

    public QueueIterator iterator() {
        return new QueueIterator();

    private class QueueIterator implements Iterator<T>{
        private Node current = first;
        public boolean hasNext(){
                return current != null;
        public T next(){
            T item = current.data;
            current = current.next;
            return item;


    private class Node{
        Node(T data){
            this.data = data;
            this.next = null;
        T data;
        Node next;
    public Queue(){
        first = last = null;
        size = 0;

    public void enqueue(T item){
        Node p = new Node(item);
        if(first == null){
            first = last = p;
        last.next = p;
        last = p;


    public T dequeue(){

       Node p = first;
            first = first.next;
        }catch(Exception e){
            System.out.println("Dequeing an empty queue :" + e);

        return p.data;


    public boolean isEmpty(){
        return last == null;


1 Answer 1

  • Bug

    dequeue doesn't set last to null when the queue becomes empty. On the other hand, isEmpty relies on last being null.

  • enqueue should be streamlined to

        if (first == null) {
            first = p;
        } else {
            last->next = p;
        last = p;

    to clearly state common vs different actions.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.