Heim  >  Fragen und Antworten  >  Hauptteil

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了

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

迷茫迷茫2742 Tage vor974

Antworte allen(2)Ich werde antworten

  • ringa_lee

    ringa_lee2017-04-18 09:52:12

    因为测试是对同一个Solution对象多次调用getRandom,你在出错的版本中修改了对象的self.head,在多次调用后self.head为None,while循环未执行,从而报错说res未定义;修改的版本则没有改变对象head,所以没有出错。

    Antwort
    0
  • 巴扎黑

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

    问题出在变量res上,getRandom()返回的是res,但变量res在返回之前,只在特定条件(满足while条件和if条件)下才被赋值。假设你的while循环体没有被执行,那么res在返回前没有被赋值,python解释器不知道该返回什么值,所以才报错。

    Antwort
    0
  • StornierenAntwort