【发布时间】: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 新手,我发现处理链表时语法有点不同
-
由于
cur是None或ListNode对象,如果用作条件,则对象为真,如果用作条件,则None为假,您可以在此将while cur写成while cur is not None的缩写。
标签: python algorithm linked-list