当前位置: 首页 > 知识库问答 >
问题:

双链接列表中removeElement()的指针存在问题

毋炳
2023-03-14

我有关于如何修改指针的问题,使用类类型元素的对象的前一个和下一个实例变量。双向链表由具有lastName、firstName、phoneNumber、前一个和下一个实例变量的Element对象填充。RemveElement方法接受lastName作为参数,并找到具有该确切String的元素,然后将其从列表中删除。然而,当修改应该从列表中删除元素的指针时,我遇到了一个异常。具体来说,在这段代码中:

previousNode.nextElement = currentNode.nextElement;
currentNode = currentNode.nextElement;
currentNode.previousElement = previousNode;

它在删除中间的一个节点之后尝试删除一个节点,然后尝试删除列表末尾的节点。因此,我肯定没有正确地修改实例变量以链接已删除元素之前和之后的元素。在遵循程序约束的同时,如何设置上一个和下一个元素的指针?

下面是代码,以防它有助于回答问题:

    package linkedlist;

import java.util.Scanner;

class Element
{
   String      firstName;        
   String      lastName;
   long        phoneNumber;
   Element     nextElement;      // Pointer to next element in the list
   Element     previousElement;  // Pointer to the last element in the list

   // Default Constructor
   public Element()
   {
      this.firstName = null;
      this.lastName = null;
      this.phoneNumber = 0;
      this.nextElement = null;
      this.previousElement = null;
   }

   // Constructor providing first and last name
   public Element( String first, String last, long number )
   {
      this.firstName = first;
      this.lastName = last;
      this.phoneNumber = number;
      this.nextElement = null;
      this.previousElement = null;
   }

   public String toString()
   {
      return( this.firstName + " "  + this.lastName + " Cell: " + this.phoneNumber);
   }
}


class ElementList
{
   Element       firstNode;
   Element       lastNode;
   public ElementList()
   {
      this.firstNode = null;
      this.lastNode = null;
   }

   public void addElement( String first, String last, long number )
   {
      Element    newNode;
      newNode = new Element( first, last, number );

      if ( this.firstNode == null)
      {
         this.firstNode = newNode;
         this.lastNode = newNode;
      }
      else
      {
         this.lastNode.nextElement = newNode;
         newNode.previousElement = this.lastNode;
         this.lastNode = newNode;
      }
   }

   public void deleteElement( String last )
   {
      Element     currentNode, previousNode = null;

      currentNode = this.firstNode; //Temporarily assigns it 
      while( currentNode != null ) //Checks if there's items.
      {
         if ( currentNode.lastName.equalsIgnoreCase( last ) == true ) //Checks the last name
         {
            // We want to delete this node
            if ( this.firstNode == currentNode )
            {
               // Delete first Node, point first node to next element
               this.firstNode = this.firstNode.nextElement;
            }
            else
            {
               /* Point the next element of the previous element to the next element
                  of the current element, thus deleting the current element
               */
               previousNode.nextElement = currentNode.nextElement;
               currentNode = currentNode.nextElement;
               currentNode.previousElement = previousNode;
            }
            break;
         }
         else
         {
            // Move to next element
            previousNode = currentNode;    // Save current node to previous
            currentNode = currentNode.nextElement;  // Move to next node
         }
      }
   }

   public void printElements()
   {
      Element     currentNode;

      System.out.println( "\nList of Elements\n================");
      if ( this.firstNode == null )
      {
         System.out.println( "No Elements in List\n" );
      }
      else
      {
         currentNode = this.firstNode;    // Point to first element
         while ( currentNode != null )    // Traverse entire list
         {
            System.out.println( currentNode );  // Print Element contents
            currentNode = currentNode.nextElement;  // Go to next node
         }
      }
   }
   public void printReverseElements()
   {
      Element currentNode;

      System.out.println( "\nList of Elements in Reverse\n================");
      if(this.lastNode == null)
      {
         System.out.println("No Elements in List\n");
      }
      else
      {
         currentNode = this.lastNode;
         while (currentNode != null)
         {
            System.out.println(currentNode);
            currentNode = currentNode.previousElement;
         }
      }
   }
}


public class LinkedList 
{
   public static void main(String[] args) 
   {
      Scanner     keyboard = new Scanner( System.in );
      ElementList list;
      String      first, last;
      double number;

      list = new ElementList();        // Instantiate the ElementList

      System.out.print( "Enter Last Name, <CR> to Exit   : " );
      last = keyboard.nextLine();             // Read last Name
      while ( last.length() != 0 )
      {
         System.out.print( "Enter First Name                : " );
         first = keyboard.nextLine();         // Read first Name
         System.out.print("Enter Phone Number              : ");
         number = keyboard.nextLong();
         list.addElement(first, last, (long) number); 
         list.printElements();// Add Element to ElementList
         if ( keyboard.hasNextLine())
         {
             keyboard.nextLine();
         }
         System.out.print( "Enter Last Name, <CR> to Exit   : " );
         last = keyboard.nextLine();
      }
      list.printElements();
      list.printReverseElements();
      System.out.print( "Enter Last Name to Delete or <CR> to Exit: " );
      last = keyboard.nextLine();
      while ( last.length() != 0 )
      {
         list.deleteElement( last );
         list.printElements();
         System.out.print( "Enter Last Name to Delete or <CR> to Exit: " );
         last = keyboard.nextLine();
      }
   }
}

或者为了方便起见,仅使用removeElement方法:

       public void deleteElement( String last )
   {
      Element     currentNode, previousNode = null;

      currentNode = this.firstNode; //Temporarily assigns it 
      while( currentNode != null ) //Checks if there's items.
      {
         if ( currentNode.lastName.equalsIgnoreCase( last ) == true ) //Checks the last name
         {
            // We want to delete this node
            if ( this.firstNode == currentNode )
            {
               // Delete first Node, point first node to next element
               this.firstNode = this.firstNode.nextElement;
            }
            else
            {
               /* Point the next element of the previous element to the next element
                  of the current element, thus deleting the current element
               */
               previousNode.nextElement = currentNode.nextElement;
               currentNode = currentNode.nextElement;
               currentNode.previousElement = previousNode;
            }
            break;
         }
         else
         {
            // Move to next element
            previousNode = currentNode;    // Save current node to previous
            currentNode = currentNode.nextElement;  // Move to next node
         }
      }
   }

作业(跳到任务5):https://drive.google.com/file/d/1POEAsdNrB3wJPI0ddsbJp2HnUay5pgei/view?usp=sharing

任何答复都将不胜感激!

共有1个答案

耿永寿
2023-03-14

从列表中删除最后一个元素时会出现问题。

按如下方式更新firstNode、lastNode对象:

public void deleteElement(String last) {
    Element currentNode, previousNode = null;
    currentNode = this.firstNode;

    while (currentNode != null) {
        if (currentNode.lastName.equalsIgnoreCase(last) == true) {
            if (this.firstNode == currentNode) {
                this.firstNode = this.firstNode.nextElement;
                if (this.firstNode != null) {
                    this.firstNode.previousElement = null;
                } else {
                    this.lastNode = null;
                }
            } else {
                previousNode.nextElement = currentNode.nextElement;
                if (currentNode.nextElement != null) {
                    currentNode = currentNode.nextElement;
                    currentNode.previousElement = previousNode;
                } else {
                    this.lastNode = previousNode;
                }
            }
            break;
        } else {
            previousNode = currentNode;
            currentNode = currentNode.nextElement;
        }
    }
}
 类似资料:
  • 我正在尝试创建二维双链接圆形阵列,从txt文件读取数据并自动创建节点。我的程序正在正确地读取第一行,但当它到达下一行并开始创建下一个节点时,会出现空指针。我不明白为什么会这样,请帮帮我。 这些都是错误。Null指针在尝试创建第二个节点时发生。它正确地创建第一个节点,而不是紧接着创建空指针。 第77行=位置next=n; 第69行=插入后(head.prev, x); 第18行=mList。镶片(k

  • 我正在制作一个方法,将一个节点添加到名为“publicvoidadd(int-index,T-value)”的列表中。 此方法将把一个值放入索引中,然后将有指向列表中下一个和上一个元素的指针。我把指向前面节点的指针搞砸了,我一直坐在那里进行实验,但没有让它工作。 示例:我们有一个包含整数值[2,4,6]实例变量的列表:Node head、tail;整数金额,变动; 内部类的实例变量为:T值;节点p

  • 下面是我当前的代码转换单链接到双向链表。我还没有接触删除功能。我已经得到插入在空列表,结束列表,开始列表显然工作。 然而,插入中间的节点似乎无法创建到前一个节点的链接。我插入的调试行似乎显示了n- 代码如下:

  • 我的双链表有两个虚拟节点,头部和尾部。函数对我来说非常适合,但是当我尝试使用与相同的算法时,它会一直为我打印虚拟节点。为什么会这样? 预期结果: 我的结果:

  • 我对C模板非常陌生。我目前正在做一个项目,我需要使用模板实现双重链接列表。以下是我目前所拥有的: 然而,在我的析构函数中,为什么我不能访问节点元素?该方法中的代码现在已编译,但不会抛出错误。但是如果我尝试使用- 此外,我如何在函数头中初始化list==NULL,而不是在类之外进行初始化?