反向单链表(不知道为什么我的代码错误)

M00000001

作为链表数据结构的学习者,我正在练习Leetcode问题“反向链表”,我有自己的解决方案,但不知道为什么错了,任何人都可以分享一些指导吗?真的很感激!

Leetcode问题:

反向单链列表。

例:

输入:1-> 2-> 3-> 4-> 5-> NULL

输出:5-> 4-> 3-> 2-> 1-> NULL

我的代码:

class Solution(object):
    def reverseList(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        prev = None
        while head:
            temp = head
            temp.next = prev
            head = head.next
            prev = temp
        return prev

但是,上述解决方案是错误的,但是可以通过如下方式在“ temp.next = prev”和“ head = head.next”之间切换位置来纠正:

class Solution(object):
    def reverseList(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        prev = None
        while head:
            temp = head
            head = head.next
            temp.next = prev
            prev = temp
        return prev

对我来说,切换两个语句之间没有什么区别,它们为什么会不同?

切普纳

这是循环开始之前的参考:

prev --> None
head --> [something| *-]-> [something| *-]-> ...

之后temp = head

prev --> None
head --> [something| *-]-> [something| *-]-> ...
         ^
         |
temp ----+

之后temp.next = prev

prev --> None
head --> [something| *-]-> None    .... -> [something| *-]-> ...
         ^
         |
temp ----+

您不再需要引用列表后面的部分。head = head.next简单地设置headNone为好。prev然后将其设置为现在被截断的列表的开头。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

我不知道为什么我的代码是错误的?那是什么错呢?

我的代码给了我一个元组错误,我不知道为什么

我不知道为什么我在 jsp 文件中收到这个简单代码的错误

SMTP 错误,我不知道为什么

Dockerfile 错误的目录。我不知道为什么

不知道为什么我收到 StopIteration 错误

我不知道为什么这段代码中有语法错误

我不知道为什么我的链表指针不动

我不知道为什么我在这段代码中出现错误。错误:列表索引超出范围

这是我的最终代码。我最终多次收到错误消息,但我不知道为什么

语法错误、意外的输入结束、期待结束 — 我的代码缺少“结束”,我不知道为什么

我的代码中不断出现“未捕获范围”错误,但我不知道为什么

复制代码后,我在 Unity 中收到错误 Unexpected symbol 'void',我不知道为什么

运行此程序时出现“无法到达的代码错误”,但我不知道为什么

我不知道为什么我收到以下错误“错误:元素类型无效:”

我不断得到细分错误:11错误,我不知道为什么... c ++

我不知道为什么我得到AttributeError

我的陈述无效,我也不知道为什么

我删除结构条目的代码没有删除,我不知道为什么

除了ValueError在我的代码中不起作用我不知道为什么

我的Matlab代码不起作用,但我不知道为什么?

R-我不知道为什么我的代码无法运行?

我的 Javascript 代码返回 null,我不知道为什么

我收到这个 Intent 的错误,我不知道为什么

我不知道为什么我得到这个文件,但是仍然显示错误

我的min(list)函数产生错误的输出,我不知道为什么

我不知道为什么python给我一个类型错误

Netsuite:我不知道为什么我的 query.load 收到此错误

我不知道为什么我得到“未定义的不是函数”错误