【问题标题】:Doubly Linked List - removal method双向链表 - 删除方法
【发布时间】:2012-03-23 22:21:28
【问题描述】:

我也在尝试通过用户输入的索引删除双向链表中的节点。这对我来说似乎很有意义,但是在“删除节点”并重新打印列表的内容之后,什么都没有改变。我敢肯定,我错过了一些愚蠢的事情。有什么建议吗?

public void removeEntryNode() {
    System.out
            .println("We delete by index here. Type in the number you want to delete");
    // print list for selection
    temp = head;
    while (temp != null && temp.getFirstName() != null) {
        System.out.print(temp.getIndex() + " " + temp.getFirstName() + " ");
        System.out.print(temp.getLastName() + " ");
        System.out.println(" ");
        temp = temp.getNext();
    }

    int selection = keyboard.nextInt();

    // Gets node matching index with selection and deletes it
    // Next two lines loop through list
    while (temp != null && temp.getIndex() != selection) {
        temp = temp.getNext();
    }

    // if it is the head
    if (selection == 0) {
        head = temp.getNext();
        temp.getNext().setPrev(null);
        temp.setNext(null);
        counter--;
    }
    // if it is the tail
    else if (selection == size()) {
        tail = temp.getPrev();
        temp.setPrev(null);
        temp.setNext(null);
        temp.getPrev().setNext(null);
        counter--;
    } else {
        temp.getPrev().setNext(temp.getNext());
        temp.getNext().setPrev(temp.getPrev());
        temp.setNext(null);
        temp.setPrev(null);
        counter--;
    }

    System.out.println("Successfully deleted ");
    menu();
}

【问题讨论】:

  • 如果这是家庭作业,那么最好在你的问题中这样说(你仍然会得到答案,但它们会为帮助你解决问题而量身定制)

标签: java doubly-linked-list


【解决方案1】:

双链表有两个指针,指向它的上一个和下一个。

如果您尝试删除该节点,请确保将 previous.next 指向节点的下一个,将 next.previous 设置为节点的上一个。

关于保持索引值,我也不同意,不过能做到完美也没关系,

【讨论】:

    【解决方案2】:

    如果不查看整个代码,就不可能查明确切的问题。

    不过,我还是给你一些指点:

    1.

    ... temp.getIndex() != selection ...
    

    链表中的元素跟踪自己的索引通常不是一个好主意。为了保持索引正确,每次插入或删除都需要遍历列表来更新索引。

    2.

        else if (selection == size()){
    

    这里可能有一个错误。

    3.

            temp.setPrev(null);
            temp.setNext(null);
            temp.getPrev().setNext(null);
    

    最后一行肯定会抛出NullPointerException

    一旦你解决了这些问题,我建议你在调试器中单步执行你的程序,看看实际发生的事情是否是你期望在每一步发生的事情。

    【讨论】:

      【解决方案3】:

      在列出所有元素后,临时指针指向列表的末尾,在搜索元素之前,应使临时指针再次指向头部。

         temp = head;
          //Gets node matching index with selection and deletes it
          //Next two lines loop through list
          while (temp!=null && temp.getIndex() != selection) {
              temp = temp.getNext();
          }
      

      【讨论】:

      • 当你删除尾巴时你会得到一个 NullPointerException:temp.getPrev().setNext(null); 你应该使用tail 而不是temp.getPrev()
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-08-27
      • 2018-09-16
      相关资源
      最近更新 更多