简体   繁体   English

如何在 python 中创建和清空链表节点?

[英]How do you create and empty linked list node in python?

According to leetcode this is the definition of a linked list根据leetcode,这是链表的定义

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next

How do you create a single node that when called outputs如何创建一个调用输出的单个节点

[]

instead of代替

[0]

In the merge two linked lists if we pass two empty nodes then the output is also an empty node, the question is how do you make an empty ListNode that has a value other than 0 or None在合并两个链表中,如果我们传递两个空节点,那么 output 也是一个空节点,问题是如何创建一个值不是0None的空ListNode

LeetCode lets you specify linked lists using Python list notation for executing tests in the browser. LeetCode 允许您使用 Python 列表符号指定链表,以便在浏览器中执行测试。 This is not how the linked list is actually represented in memory;不是链表在 memory 中实际表示的方式; LeetCode runs code on their backend to take the list you input as a test case and turn it into a linked list. LeetCode 在其后端运行代码,将您输入的列表作为测试用例,并将其转换为链表。

If you're trying to test your code locally and want to represent an empty linked list, use None rather than [] .如果您尝试在本地测试代码并希望表示一个空链表,请使用None而不是[] A linked list with one node can be declared as follows:一个节点的链表可以声明如下:

singleton_linked_list = ListNode(5) # Creates a new linked list with one node.

If you want to create Empty Linked List and assuming head is given.如果你想创建空链表并假设 head 被给出。

curr = head
curr.next = None
curr = curr.next

You can use the following while solving your problem in LeetCode:在 LeetCode 中解决问题时,您可以使用以下内容:

if not lists:
   return None
if len(lists) == 1:
   return lists[0]

Thus, whenever there is input like [] or [[]] , so after execution LeetCode compiler will return an empty List with None.因此,只要有像[][[]]这样的输入,在执行之后 LeetCode 编译器将返回一个空的列表,其中没有。

I had the same problem as you but I just figured it out.我和你有同样的问题,但我只是想通了。 All you have to do is return None and Leetcode will accept it.你所要做的就是返回 None 并且 Leetcode 会接受它。 I tested it on Leetcode problem 23, Merge k Sorted Lists.我在 Leetcode 问题 23,Merge k Sorted Lists 上对其进行了测试。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM