我有这样一个ListNode
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
和一个链表
Input: l1: 1->2->4, ll2:1->3->4
如何将数字添加到列表中?
我尝试了
head = ListNode(0)
node1 = ListNode(head)
node1.next = node2 #but node2 has not been declared
node2 = ListNode(2)
node2.next = node3 #node3 has not been declared
node3 = ListNode(4)
node3.next = null
我认为我需要一些d = defaultdict(int).
之类的Listnode东西,然后可以在分配之前使用d []。
答案 0 :(得分:1)
我可以通过在节点类中添加工厂方法来解决此问题-
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
def link(value):
node = ListNode(value)
self.next = node
return node
然后您的初始化代码将变为...
head = ListNode(0)
head.link(2).link(4).link(6)
答案 1 :(得分:1)
这将运行:
head = ListNode(0)
node1 = ListNode(head) # <-- is this really what you want
node2 = ListNode(2)
node3 = ListNode(4)
node1.next = node2
node2.next = node3
node3.next = null # <-- or maybe it won't
但这不是您想要的吗
head = ListNode(0)
node1 = ListNode(1)
node2 = ListNode(2)
node3 = ListNode(4)
head.next = node1
node1.next = node2
node2.next = node3
# node3.next = None # <-- this is redundant
如果您这样定义班级:
# Definition for singly-linked list.
class ListNode:
def __init__(self, x, next=None):
self.val = x
self.next = next
您可以这样做:
head = ListNode(0, ListNode(1, ListNode(2, ListNode(4))))
但是也许您想要所有对节点的中间引用