0

I am learning the Queue Data structure.I want to create Queue with linked list.I want to program ouput : 10 20 Program output: Queue empty -1 Queue empty -1

Where am I making mistakes?

The code is as given below:

class Node {
  int x;
  Node next;

  Node (int x){
    this.x=x;
    next=null;

}

}

public class QueQueLinked {
 static Node root=null;
 static Node latest=null;

 public static void enque(int x){
    if(root==null){
        Node root=new Node(x);
        root.x=x;
        root.next=null;
        latest=root;
    }

    else{
        latest.next=new Node(x);
        latest=latest.next;
        latest.next=null;


    }

}

public static int deque(){
    if(root==null){
        System.out.println("Queque empty");
        return -1;

    }
    int value=root.x;
    root=root.next;

    return value;
}

public static void main(String[] args) {
   enque(10);
   enque(20);

    System.out.println(deque());
    System.out.println(deque());
}

}

2 Answers 2

2

You are overwriting your root variable. You need to do:

public static void enque(int x){
    if(root==null){
        root=new Node(x);
        root.x=x;
        root.next=null;
        latest=root;
    }
Sign up to request clarification or add additional context in comments.

Comments

2

Your error is in this line:

Node root=new Node(x);

You are creating a new local variable named root that hides the the static field root. Instead you should write:

root=new Node(x);

If you have a local variable root that hides the static field root you could also access the static field by prepending it with your class name:

QueQueLinked.root = new Node(x)

In this case, however, you should rethink your variable names.

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.