【问题标题】:Reverse Linked List (reference to next node)反向链表(参考下一个节点)
【发布时间】:2017-08-11 08:08:11
【问题描述】:

我正在研究一个要求反转链表的问题:

例子:

对于链表1->2->3,反向链表为3->2->1

这是我的代码:

"""
Definition of ListNode

class ListNode(object):

    def __init__(self, val, next=None):
        self.val = val
        self.next = next
"""
class Solution:
    """
    @param head: The first node of the linked list.
    @return: You should return the head of the reversed linked list. 
                  Reverse it in-place.
    """
    def reverse(self, head):
        # write your code here
        prev = None
        current = head
        next = current.next
        while(current is not None):
            current.next = prev
            prev = current
            current = next
            next = next.next
        head = prev
        return prev

提交后出现错误。谁能帮我指出为什么它是错误的? 错误消息是说“next = current.next AttributeError: 'NoneType' object has no attribute 'next'”。我尝试使用 next 引用当前节点旁边的节点。

谢谢!

【问题讨论】:

  • 请发布完整的回溯
  • 我认为您需要在执行逻辑之前检查 head 是否为 None。如果 head 是 None 你只需要返回它。
  • 始终考虑各种测试用例。例如,空列表、包含一个、两个...项目的列表等。
  • @VitalieMaldur :不 - 请参阅 Miriam Farber 的回答,它避免了任何特殊情况。 (链表代码的第一条规则:“没有特殊情况” - 你会错过一个。)

标签: python linked-list


【解决方案1】:

您正在尝试访问next.next,但next 可能是None(您检查了current 是否为None,但您没有检查next 是否为None。@987654328 @ 在循环的最后一次迭代中确实是 None)。 因此,您需要在循环内移动next=current.next,并删除循环中的最后一行,如下所示:

def reverse(self, head):
        # write your code here
        prev = None
        current = head
        while(current is not None):
            next = current.next
            current.next = prev
            prev = current
            current = next
        return prev

【讨论】:

  • 现在知道了。谢谢米里亚姆!!
  • 这个是正确的答案 - 请注意,没有特殊情况。一个小问题,在你返回之前分配给head是没有意义的——它是一个局部变量。
【解决方案2】:

问题出现在最后一种情况下。当 current 等于列表中的最后一个节点时,您将 next 分配给等于 next.next。问题是此时的 next 等于 null,所以你说的 null 等于 null.null 这会导致你的错误。您可能应该将您的 while 循环条件更改为

while(next is not None):

并在后面的部分中更改添加以更新列表中的最终节点以指向前一个节点

current.next = prev
head = prev
return prev

【讨论】:

    猜你喜欢
    • 2012-06-20
    • 1970-01-01
    • 2019-05-19
    • 2023-03-15
    • 2016-07-09
    • 1970-01-01
    • 1970-01-01
    • 2015-08-16
    • 1970-01-01
    相关资源
    最近更新 更多