【问题标题】:Why does my reverse linked list only return head?为什么我的反向链表只返回头部?
【发布时间】:2018-04-04 18:38:02
【问题描述】:

我在做反向链表leetcode问题:反向单链表。 但是我的代码只返回头部,尽管我认为头部通过以下方式与其下一个节点链接:

pre = curr.next  

下面是我的代码。我很难弄清楚问题出在哪里。任何帮助表示赞赏!

class Solution(object):
    def reverseList(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        if head == None:
            return head

        pre, curr, post = None, head, head.next
        while post:
            pre = curr.next
            pre, curr, post = curr, post, post.next

        pre = curr.next

        return curr

【问题讨论】:

  • 你不是在建立一个新的、反向的列表;您只是将原始列表走到最后。
  • 我认为您的线路pre = curr.next 可能是错误的方式。试试curr.next = pre

标签: python list linked-list reverse


【解决方案1】:

在linkedlist中,节点使用下一个变量连接(在leetcode中给出)。您所做的只是简单地向前推进,而不会颠倒它们之间的关系。

你应该做的是

class Solution(object):
def reverseList(self, head):
    """
    :type head: ListNode
    :rtype: ListNode
    """
    if head == None:
        return head

    pre, curr, post = None, head, head.next
    while post:
        curr.next=pre
        pre, curr, post = curr, post, post.next
    curr.next=pre

    return curr

我希望你能看到哪里出错了。代码的手迹总是有助于理解逻辑。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-22
    • 2021-06-05
    • 1970-01-01
    • 1970-01-01
    • 2010-11-30
    相关资源
    最近更新 更多