【问题标题】:Question about Reverse Linked List (leetcode 206)关于反向链表的问题(leetcode 206)
【发布时间】:2020-08-31 07:11:08
【问题描述】:

我知道我的代码完全错误,但我不知道我哪里做错了,

谁能指出并解释我做错了什么?

public ListNode reverseList(ListNode head) {
    if (head == null) {
        return head;
    }
    
    ListNode prev = null;
    ListNode current = head;
    ListNode nextNode = head.next;
    
    while (nextNode != null) {
        prev = current;
        current = nextNode;
        current.next = prev;
        nextNode = nextNode.next;
        System.out.println(nextNode.val);
    }
    
    return current;
}

【问题讨论】:

  • 看你执行的顺序current.next = prev;nextNode = nextNode.next; - currentnextNode在这两行之前指的是同一个节点,那么你认为执行时会发生什么他们
  • 这是 Java 吗?如果是这样,您可能希望将标签添加到问题中。

标签: algorithm data-structures linked-list


【解决方案1】:

变化:

  1. head.next = null; // 使列表的结尾为空

  2. current.next = prev; // current 是对节点的引用,所以对它的更改也会改变引用 nextNode 的节点

    public ListNode reverseList(ListNode head) {
         if (head == null) {
             return head;
         }
    
         ListNode prev = null;
         ListNode current = head;
         ListNode nextNode = head.next;
         head.next = null;   // to make the end of the list as null
    
         while (nextNode != null) {
             prev = current;
             current = nextNode;
             nextNode = nextNode.next;   // first get next node, before ...
             current.next = prev;        // ... overwriting it here
             // System.out.println(nextNode.val);
         }
    
         return current;
     }
    

【讨论】:

    【解决方案2】:

    替代方案

    我们可以只说while head != null,然后使用prev 节点将其反转,最后我们将返回prev。这会更容易:

    public final class Solution {
        public static final ListNode reverseList(ListNode head) {
            ListNode prev = null;
            ListNode nextNode;
    
            while (head != null) {
                nextNode = head.next;
                head.next = prev;
                prev = head;
                head = nextNode;
            }
    
            return prev;
        }
    }
    

    【讨论】:

    • 虽然你的代码更优雅,但呈现全新的代码并不能帮助人们了解为什么他的代码不起作用。 @yash-shah 的回答更有帮助,因为它指出了我们在哪里更改他的代码。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-06-12
    • 1970-01-01
    • 2021-12-02
    • 2022-11-04
    • 1970-01-01
    • 2019-01-09
    • 1970-01-01
    相关资源
    最近更新 更多