【问题标题】:What is wrong in my code to reverse a linked list?我的代码反转链表有什么问题?
【发布时间】:2017-02-28 17:28:58
【问题描述】:

我正在尝试解决一个简单的 leetcode 问题:

反转单链表。 link

这是我的代码:

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
public class Solution {
    public ListNode reverseList(ListNode head) {
        if (head == null)
        {
            return head;
        }
        ListNode prev = null;
        while (head != null && head.next != null)
        {
            ListNode current = head;
            current.next = prev;
            prev = head; // I think the problem is with this statement
            head = head.next;
        }
        return head;
    }
}

我要做的是遍历列表的所有节点,并在每一步通过将前一个节点保存在 ListNode 变量中来将当前节点链接到前一个节点。

这是测试用例和输出,可以让您更轻松。

输入:[1,2] 输出:[] 预期:[2,1]

再一次,我并不是真的在寻找替代解决方案或递归解决方案。我只想知道我的代码有什么问题(如果适用,还有逻辑)。

【问题讨论】:

    标签: java algorithm data-structures linked-list


    【解决方案1】:

    您的代码实际上只进行了一次迭代,因为它的工作方式如下:

    ListNode current = head;
    // You assign head.next to prev here
    // which is equal to null for the first iteration
    current.next = prev;
    prev = head; 
    // And here you go to head.next, which was set to null above
    head = head.next;
    // The head is null, so the while loop ends
    

    由于您没有要求正确的解决方案,我只是提示如何解决它:您应该在将 head.next 分配给 prev 之前将其存储在某处。

    【讨论】:

      【解决方案2】:

      在覆盖之前忘记保存 head.next。

      当您将 head 分配给 ListNode 当前时,您只是分配一个引用,而不是复制节点。所以current 完全是head 的同义词(而且是多余的)。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-07-24
        • 2015-02-16
        • 1970-01-01
        • 2011-07-28
        相关资源
        最近更新 更多