Python 将元素写入Linkedlist

Python 将元素写入Linkedlist,python,Python,我有这样一个列表节点 # 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

我有这样一个列表节点

# 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

我想我需要一些Listnode的东西,比如
d=defaultdict(int)。
然后我可以在赋值之前使用d[.

我会通过向我的节点类添加工厂方法来解决这个问题-

单链表的定义。 然后初始化代码变成

head = ListNode(0)
head.link(2).link(4).link(6)
这将运行:

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, ListNode(1, ListNode(2, ListNode(4))))

但是,您可能需要所有对节点的中间引用

为什么不在从
node1
链接到节点之前创建
node2
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))))