【问题标题】:NullPointerException LinkedList reverse methodNullPointerException LinkedList 反向方法
【发布时间】:2021-09-12 19:05:04
【问题描述】:

我被困在这个练习中,我必须为双向链表实现一个反向方法,它可以反转整个列表。我的 for 循环中出现 NullPointerException,我不确定如何解决它,因为在练习中指出我不应该创建新的 IntNode 实例。即使我使用 if-else 语句 if(current.next != null) ... 任何帮助将不胜感激!

void reverse() {
        IntNode temp1;
        IntNode temp2;
        // TODO: Vervollständigen Sie die Methode wie in der Aufgabenstellung gefordert.
        
        this.last.next = this.last.prev;
        this.last.prev = null; 
        
        for (IntNode current = this.last.next; current != this.first; current = current.prev) {
                temp1 = current.next;

            current.next = current.prev;
            current.prev = temp1;
        }
        this.first.prev = this.first.next;
        this.first.next = null;
        
        temp2 = this.first;
        this.first = this.last;
        this.last = temp2;
    }

【问题讨论】:

  • 这能回答你的问题吗? What is a NullPointerException, and how do I fix it?。你应该花时间调试你的程序,逐行检查,或者只是阅读堆栈跟踪来识别导致问题的行。
  • 你好 helloworld123。欢迎来到堆栈。您是否用纸手工浏览过代码,并为导致问题的简单案例记下变量的最新值?
  • 欢迎来到 SO。请提供一个完整的可执行示例:您获得异常的完整类和执行数据。最好的问候。

标签: java linked-list nullpointerexception null doubly-linked-list


【解决方案1】:

因此,对于您要交换当前节点的 next 和 prev 的每个节点,for 循环中的增量条件应该是 current = current.next 而不是 current = current.prev。

    void reverse() {
        IntNode temp1;
        IntNode temp2;
    
        this.last.next = this.last.prev;
        this.last.prev = null; 
    
        for (IntNode current = this.last.next; current != this.first; current = current.next) {
            temp1 = current.next;

            current.next = current.prev;
            current.prev = temp1;
        }
        this.first.prev = this.first.next;
        this.first.next = null;
    
        temp2 = this.first;
        this.first = this.last;
        this.last = temp2;
    }

【讨论】:

    【解决方案2】:

    交换时,下一个要交换的元素成为当前检查节点的next。所以你需要为循环的下一次迭代设置current = current.next

    你也不需要在循环外交换最后一个和第一个元素,你可以在里面做这个,当你改变for循环的条件时:从last节点开始直到检查@ 987654324@ 是null

    根据您的代码,这是一个略短的解决方案:

    public void reverse() {
      for (IntNode current = this.last; current != null; current = current.next) {
        IntNode temp1 = current.next;
        current.next = current.prev;
        current.prev = temp1;
      }
      
      IntNode temp2 = this.first;
      this.first = this.last;
      this.last = temp2;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-07-05
      • 2013-04-06
      • 1970-01-01
      • 2014-05-19
      • 2017-04-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多