简体   繁体   English

如何使用双向链表在另一个节点之后插入一个节点?

[英]How to insert a node after another node using doubly linked list?

I want to insert a node after another node in a doubly-linked list but when I provide such a key that doesn't exist in the Linked list then this method gives me an error.我想在双向链接列表中的另一个节点之后插入一个节点,但是当我提供链接列表中不存在的此类键时,此方法会给我一个错误。 How should I fix this error?我应该如何解决这个错误? here is my code.这是我的代码。 Thanks in Advance.提前致谢。

{
   public void AddAfter(int insertAfter, int data) 
   {
   DLNode n = new DLNode(data);
   DLNode curr = head;
   if(head == null)
       head = n;
   else
   {
       while(curr.Data != insertAfter && curr != null) 
       {
           curr = curr.next;
       }
       if(curr != null) 
       {
           n.next = curr.next;
           n.prev = curr;
           n.next.prev = n;
           curr.next = n;
           NumNodes++;
           
           
       }
       else
           System.out.println("The Key "+insertAfter+" doesn't exist: ");
   }
  }
}

... but when I provide such a key that doesn't exist in the Linked list then this method gives me an error. ...但是当我提供链接列表中不存在的此类密钥时,此方法会给我一个错误。

The problem occur in your while loop condition (eg, curr.Data != insertAfter && curr != null ).问题出现在您的 while 循环条件中(例如, curr.Data != insertAfter && curr != null )。 Here, you are first accessing the data field of the curr variable and then checking whether curr is null or not.在这里,您首先访问curr变量的data字段,然后检查curr是否为 null。

How should I fix this error?我应该如何解决这个错误?

You need to do it in reverse order.您需要以相反的顺序执行此操作。 The following code should solve your problem.以下代码应该可以解决您的问题。

public void AddAfter(int insertAfter, int data) {
    DLNode n = new DLNode(data);
    DLNode curr = head;
    
    if(head == null) {
        head = n;
    }
    else {
        while(curr != null && curr.Data != insertAfter) {
            curr = curr.next;
        }
        if(curr != null) {
            n.next = curr.next;
            n.prev = curr;
            n.next.prev = n;
            curr.next = n;
            NumNodes++;
        }
        else {
            System.out.println("The Key "+insertAfter+" doesn't exist: ");
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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