简体   繁体   中英

Insert generic element at a specific index in Doubly linked List java

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM