python - leetcode返回单链表任意节点,提示未声明?
迷茫
迷茫 2017-04-18 09:50:12
0
2
957

就是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了

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

迷茫
迷茫

业精于勤,荒于嬉;行成于思,毁于随。

reply all(2)
左手右手慢动作

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.

巴扎黑

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.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!