在i和j / while j和我在python中时不同

时间:2018-01-13 04:53:10

标签: python data-structures

我正在尝试执行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不起作用?

1 个答案:

答案 0 :(得分:1)

它被称为short circuit evaluation。如果cur为None,则解释器甚至不会尝试检查cur.next。