0

I have a function in my Doubly linked list class to insert an element is given index. So I made some codes that did not work.The error they said is "Cannot read field "prev" because "current" is null" .

Here is my code:

public void add(int key, E data){
    if(key<0 || key>size){
        return;
    }
    else{
        Node current = head;
        if (key==0){
            Node newLink = new Node(data);

            if (size==0)
                tail = newLink;
            else
                head.prev = newLink;
            newLink.next = head;
            head = newLink;
        }
        else{
            for(int i=0;i<key;i++){
                current= current.next;
            }
            Node newNode= new Node(data);
            newNode.next=current;
            newNode.prev=current.prev;
            size++;
        }
    }
}

Please help me how can I get the way to overcome this problem.

3
  • What is the input you are running on? The first thing I see is that you are not advancing your size every place that is needed only in one of the cases Commented Jun 7, 2021 at 10:50
  • a.add("fff"); a.add("dfgh"); a.add(1, "dd") Commented Jun 7, 2021 at 10:57
  • This kind of inputs as I already have another function to add by data. @SgtOmer Commented Jun 7, 2021 at 10:58

1 Answer 1

1

There was a few problems I saw in the code you provided. Firstly you are not advancing size in every place needed. Secondly, the for loop to advance the current is going one step further than needed.

Here is my take:

public void add(int key, E data){
    if(key<0 || key>size)
        return;
    Node current = head;
    if (key==0){
          Node newLink = new Node(data);
          if (size==0)
              tail = newLink;
          else
              head.prev = newLink;
          newLink.next = head;
          head = newLink;
   } else{
          for(int i=0;i<key-1;i++){
              current= current.next;
          }
          Node newNode= new Node(data);
          newNode.next=current;
          newNode.prev=current.prev;
  }
  size++;
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you man. i understand it now. Appreciate it.

Your Answer

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