【发布时间】:2023-03-03 02:14:01
【问题描述】:
我正在尝试做 leetcode #83 我不明白的是以下两种方式有什么区别:
while cur and cur.next:
while cur.next and cur:
如果我尝试第二种方式,它会出现编译错误。 谁能帮我理解这个概念?
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def deleteDuplicates(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
cur= head
while cur and cur.next:
if cur.val== cur.next.val:
cur.next= cur.next.next
else:
cur = cur.next
return(head)
我是数据结构的初学者。 我仍然困惑为什么 cur.next 是错误方式。代码 cur = head 不起作用?
【问题讨论】:
-
给您和读者的小提示:
None的比较应该是definitely be done withis:while cur is not None and cur.next is not None。 -
不同意。
while cur and cur.next是惯用的。与None比较时,PEP8 只说使用is而不是==。它并不坚持使用value is not None而不是简单的value。