[英]How to create my own input for Python linked list questions?
我刚开始通过 LeetCode 学习 Python。 我在问题 876“链接列表的中间”。 解决方案如下:
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution(object):
def middleNode(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
slow = fast = head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
return slow
来自 LeetCode,当输入为 [1,2,3,4,5] 时,output 为 [3,4,5]。 请问我在自己的 IDE 中运行此代码时如何创建自己的输入? 我尝试了以下
head = ListNode([1,2,3,4,5])
print(Solution().middleNode(head))
但它没有向我显示正确的 output [3,4,5],而是显示“进程以退出代码 0 完成”
非常感谢!
为了方便起见,LeetCode 允许您使用 Python 列表表示法指定链接列表,因为您可以在浏览器中执行自定义单元测试。 function实际上并不包含链表; 如果您在本地运行东西,则必须将普通 Python 列表转换为链表。
您所做的转换不太正确:您所做的是创建了一个新的 ListNode,它的val
字段设置为列表[1, 2, 3, 4, 5]
,并且它的next
字段设置为 None .
这是您要查找的内容(遍历输入列表中的每个元素,并将它们插入到链表中):
def convert_to_linked_list(input_list):
head = None
for i in range(len(input_list) - 1, -1, -1):
new_head = ListNode(input_list[i], head)
head = new_head
return head
当我最终运行此代码时,它看起来正在生成 output:
<__main__.ListNode object at 0x000001DCF7B5EFD0>
Process finished with exit code 0
它似乎不是您所期望的 output。 当我调试代码时,middleNode 似乎跳过了 while 循环,因为默认情况下 ListNode class 下一个是 None ,在 python 中被评估为 false。 所以它只是返回慢,也就是原来的ListNode。
你需要两个功能:
middleNode
) 我建议向ListNode
class 添加方法。 第二个实际上可能是__iter__
以便链表变得可迭代,然后您只需将*
运算符放在您的 print 语句中:
class ListNode(object):
def __init__(self, val=0, next=None):
self.val = val
self.next = next
@classmethod
def of(Cls, lst):
head = None
for val in reversed(lst):
head = Cls(val, head)
return head
def __iter__(self):
head = self
while head:
yield head.val
head = head.next
class Solution(object):
def middleNode(self, head):
slow = fast = head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
return slow
head = ListNode.of([1,2,3,4,5])
print(*Solution().middleNode(head))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.