0

I want to program a enqueue(elem) in Java, so I have programmed the following modules:

public class Node{
    public int e;
    Node next;
    public Node(int e){
        this.e=e;
    }
}

and now I want to use a Linked List to store my elements, so I made a class with a enqueue() function like this:

 public class Queue{
        Node q;        //represents a queue 
        Node first;
         public void enqueue(int n){
            Node t=new Node(n);  //represents a temporal node
            if(q==null){
                first=t;
            }
            else{
                t.next=first;
                t=first;
            }
            q=t;  //to store the node into the queue
        }
}

but when I want to print the elements of my queue:

 public void print(){
            Node current=first;
            while (current!=null){
                System.out.println(current.e);
                current=current.next;
            }
        }

it only prints me the first element that I enter, for example if I put 10,20,30,40 it only prints 10. What am I doing wrong?

Thanks

6
  • q should be your queue tail? Commented May 26, 2019 at 15:25
  • I don't see how your print routine works. How are you updating current? And next isn't being used. Commented May 26, 2019 at 16:17
  • the first thing you are doing wrong is unclear identifiers. Is "q" "lastNode"? Is "t" "newLastNode"? Commented May 26, 2019 at 16:26
  • @michalk not really, q represents my queue in the form of a linked list Commented May 26, 2019 at 18:39
  • @AlexeiKaigorodov, thanks for pinpointing those errors I made when translating my code; now I have fixed them Commented May 26, 2019 at 18:40

1 Answer 1

1

Your code for the class Queue should be the below. The node first will be the first element and q will be the last element.

public class Queue{
    Node q;
    Node first;
     public void enqueue(int n){
        Node t=new Node(n);
        if(q==null){
            first=t;
        }
        else{
            q.next=t;
        }
        q=t;
    }
     public void print(){
         Node current=first;
         while (current!=null){
             System.out.println(current.e);
             current = current.next;
         }
     }
}
Sign up to request clarification or add additional context in comments.

Comments

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.