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

查看:172
本文介绍了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了

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

解决方案

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

这篇关于python - leetcode返回单链表任意节点,提示未声明?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆