2

I am trying to do leetcode #83 The thing I don't understand is that what's a difference between the following two ways:

    while cur and cur.next:

    while cur.next and cur:

If I try the second way, it will appear compile error. Can anyone help me to understand this concept?

    # 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)

I am the beginner of data structure. I still confuse why cur.next is error way. The code cur = head didn't works?

Esther
  • 31
  • 3
  • Just a tip for you and readers: Comparison for `None` should [definitely be done with `is`](https://www.python.org/dev/peps/pep-0008/#programming-recommendations): `while cur is not None and cur.next is not None`. – TerryA Jan 13 '18 at 04:59
  • 2
    Disagree. `while cur and cur.next` is idiomatic. PEP8 only says to use `is` rather than `==` when comparing to `None`. It doesn't insist that one use `value is not None` over simply `value`. – John Kugelman Jan 13 '18 at 05:02

1 Answers1

1

It's called short circuit evaluation. If cur is None, the interpreter won't even try to check cur.next.

Armandas
  • 2,276
  • 1
  • 22
  • 27
  • I still confuse why cur.next is error way. The code cur = head didn't works? Why cur is None? – Esther Jan 13 '18 at 05:58
  • @Esther you loop through a linked list, when you reach the end, cur will become None because of `cur = cur.next`. – Armandas Jan 13 '18 at 06:08