【问题标题】:Python, linked listPython,链表
【发布时间】:2021-02-21 09:36:33
【问题描述】:

这是来自 leetcode 的一个问题:

定义一个函数,输入一个链表的头节点,取反 链表。

示例:

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

这是官方的回答:

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next

class Solution:
    def reverseList(self, head: ListNode) -> ListNode:
        cur , pre = head, None
        while cur:
            tmp = cur.next  
            cur.next = pre 
            pre = cur
            cur = tmp 
        return pre

我想问一下while cur:这行是什么意思?它是否横穿整个链表?我尝试用while head:替换它,为什么自从cur == head之后它不起作用?

【问题讨论】:

  • 因为你在循环中改变了cur,所以你没有改变head
  • cur 是指向您正在观察的当前节点的指针。请参阅 cur 正在更改为 cur.next。因此,当您位于 tail 时,cur 将是 None,因此 while 循环将中断。
  • 好的,谢谢。但是我怎么理解“while cur”,它和“while cur != None”一样吗?我是 python 新手,我发现处理链表时语法有点不同
  • 由于curNoneListNode 对象,如果用作条件,则对象为真,如果用作条件,则None 为假,您可以在此将while cur写成while cur is not None的缩写。

标签: python algorithm linked-list


【解决方案1】:
while cur:

意思

while cur is not None:

来自documentation

在布尔运算的上下文中,以及当控制流语句使用表达式时,以下值被解释为假:假、无、所有类型的数字零以及空字符串和容器(包括字符串、元组、列表、字典、集合和冻结集合)。所有其他值都被解释为 true。


现在,您的循环遍历输入链表的节点,并在运行中反转“箭头”(指针)的方向:

为了达到这个目标,在每次迭代中,它首先将下一个当前节点保存在 temp 变量 (tmp = cur.next) 中,以使其在循环结束时成为当前节点 (cur = tmp) — 用于下一次迭代.

中间的 2 命令改变箭头的方向 (cur.next = pre) — 所以“下一个”将是 previous 节点 — 并准备 pre 变量 (pre = cur)下一次迭代。

【讨论】:

  • 图片不错。它让我想起了以None 作为机车的火车。 “我们回去吧”——机车将自己(通过铁路道岔)重新定位到火车的另一侧,将其拉向相反的方向。 :-)
【解决方案2】:
class Solution:
    def reverseList(self, head: ListNode) -> ListNode:
        cur , pre = head, None
        while cur:
            tmp = cur.next  
            cur.next = pre 
            pre = cur
            cur = tmp 
        return pre

以上等价于:

class Solution:
    def reverseList(self, head: ListNode) -> ListNode:
        cur , pre = head, None
        while cur is not None:
            tmp = cur.next  
            cur.next = pre 
            pre = cur
            cur = tmp 
        return pre

【讨论】:

    猜你喜欢
    • 2019-03-13
    • 1970-01-01
    • 1970-01-01
    • 2013-02-13
    • 2012-02-17
    • 2018-03-28
    • 2016-03-23
    • 2020-06-28
    • 2021-10-13
    相关资源
    最近更新 更多