HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavaMinor

Queue implementation in Java

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
implementationqueuejava

Problem

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

import java.util.Iterator;

public class Queueimplements Iterable {

    private Node first, last;
    private int size;

    @Override
    public QueueIterator iterator() {
        return new QueueIterator();
    }

    private class QueueIterator implements Iterator{
        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;
            size++;
            return;
        }
        last.next = p;
        last = p;
        size++;

    }

    public T dequeue(){

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

        return p.data;

    }

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

}

Solution

-
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;
    size++;


to clearly state common vs different actions.

Code Snippets

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

Context

StackExchange Code Review Q#114784, answer score: 5

Revisions (0)

No revisions yet.