Home  >  Q&A  >  body text

python - leetcode返回单链表任意节点,提示未声明?

就是leetcode382
Linked List Random Node

Given a singly linked list, return a random node's value from the linked list. Each node must have the same probability of being chosen.

然后我写的问题如下:

但是把self.head用新变量head,s或者其他什么字母声明一下,改成:

    ···
    cnt = 0
    head = self.head
    while head:
        if random.randint(0, cnt) == 0:
            ans = head.val
        head = head.next
        cnt += 1
    return ans

就通过了,AC了

为什么啊? 谢谢,实在不懂, 出错的那个测试用例我也不明白,这么多中括号表示什么啊?

迷茫迷茫2764 days ago1000

reply all(2)I'll reply

  • ringa_lee

    ringa_lee2017-04-18 09:52:12

    Because the test calls getRandom multiple times on the same Solution object, you modified the object's self.head in the wrong version. After multiple calls, self.head is None, and the while loop is not executed, so an error is reported saying res is undefined. ;The modified version does not change the object head, so there is no error.

    reply
    0
  • 巴扎黑

    巴扎黑2017-04-18 09:52:12

    The problem is that the variable res上,getRandom()返回的是res,但变量res在返回之前,只在特定条件(满足while条件和if条件)下才被赋值。假设你的while循环体没有被执行,那么res is not assigned a value before returning. The python interpreter does not know what value to return, so it reports an error.

    reply
    0
  • Cancelreply