python - 自动化构建 LinkedList 的过程

标签 python

我有这样一个LinkedList

Given linked list: 1->2->3->4->5,

class ListNode:
    def __init__(self, x):
        self.val = x
        self.next = None

然后必须手动构建 LinkedList。

    head = ListNode(1)
    node1 = ListNode(2)
    node2 = ListNode(3)
    node3 = ListNode(4)
    node4 = ListNode(5)
    head.next = node1
    node1.next = node2
    node2.next = node3
    node3.next = node4
    node4.next = None

是否可以自动化该过程,例如

for i in range(1, 6):
    node(i-1) = ListNode(i) #made up the node(i-1)

最佳答案

您可以通过以下方式将可迭代对象(例如 list)转换为 LinkedList:

def generate_linked_list(nums):
    cur = dummy = ListNode(0)
    for num in nums:
        cur.next = ListNode(num)
        cur = cur.next
    return dummy.next

dummy节点用于nums为空的情况。

或者使用 self 而不使用 dummy 节点的技巧,如果它是类函数:

class LinkedList:
    def generate_linked_list(self, nums):
        cur = self
        for num in nums:
            cur.next = ListNode(num)
            cur = cur.next
        return self.next

用法:

head = generate_linked_list([1, 2, 3, 4, 5])

关于python - 自动化构建 LinkedList 的过程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55593908/

相关文章:

python - Pandas DataFrame .style.format 不工作

python - 在Elasticsearch中对大量文档进行排序

python - 过滤复杂列表中的元素

python - 2-dim 字典,键为字符串

使用 kwargs 时的 Python 2 和 3 元类兼容性

Python for 循环未运行

python - 将一段时间内的观察结果展平为单行

python /灰鲭鲨 : Script Tag not showing up from Sub Template when Loaded into Main Template via Ajax Call

python - 类装饰器问题,或: How does Python discriminate methods from staticmethods?

python - 如何使用 pytest 在 Django 中测试重定向?