2

I am trying to write my own queue class. My enqueue method is only enqueue-ing one object and then if I try to enqueue anything else, its almost as if its ignoring it. Here is my code:

public class myQueue {

    private Node front;
    private Node back;
    private int s;

    public myQueue() {
            front = null;
            back = null;
            s = 0;
    }

    public void enqueue(Object x) {
        if( isEmpty() )
            back = front = new Node(x);
        else
            back = back.next = new Node(x);
        s++;
    }

    public Object dequeue() {
        Object x;
        if( isEmpty() ) { System.out.println("nothing to dequeue.\nqueue empty."); }
        x = front.data;
        s--;
        return x;
    }

    public boolean isEmpty() {
        if(s == 0)
            return true;
        else
            return false;
    }

    public void printQueue() {
        if ( isEmpty() )
            System.out.println("empty queue");
        else {
            Node temp = back;
            while(temp != null) {
                System.out.println(temp);
                temp = temp.next;
            }
        }   
    }



}

and here is my main method where i try to enqueue some objects:

public static void main(String[] args) {
    int a = 5;
    String b = "yo";
    Object c = 5.5;                
    int d = 2;
    String e = "Pen";
    Object f = 9.2;

    myQueue q = new myQueue();

    q.enqueue(a);
    q.enqueue(b);
    q.enqueue(c);
    q.enqueue(d);
    q.enqueue(e);
    q.enqueue(f);

    System.out.println("\n");

    q.printQueue();
}

and then all i get for output is:

data: 9.2

any ideas as to why this is happening?

1 Answer 1

2

When you print, you are starting at the back of the queue, you should start at the front:

        Node temp = front; // <<< replacing back by front
        while(temp != null) {
            System.out.println(temp);
            temp = temp.next;
        }

If you start at the back of the queue, you will only have the last element of the queue to be printed...

My result with the fix:

data : 5
data : yo
data : 5.5
data : 2
data : Pen
data : 9.2
Sign up to request clarification or add additional context in comments.

1 Comment

ah that seems so obvious, thanks. For whatever reason i had them drawn in my notebook linked back to front, not front to back, so i was thinking i had to print starting from the back. thank you!

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.