【发布时间】: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