如何在Python中创建链表

4

我正在尝试用Python解决一个链表编程挑战。我只提供以下类来创建链表。

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

我可以创建一个类似这样的链表。
x = ListNode(1)
x.next = ListNode(4)
x.next.next = ListNode(5)

然而,我如何在for循环内部创建迭代对象?

3个回答

3
你需要两个“指针”来记忆链表的头部和尾部。头部仅被初始化一次,最终你会用它来访问整个列表。尾部每次添加另一个节点时都会改变。
data = [5, 1, 7, 96]
tail = head = ListNode(data[0])
for x in data[1:]:
    tail.next = ListNode(x) # Create and add another node
    tail = tail.next # Move the tail pointer

0
你可以这样做:
arr = [1,4,5]
for i in arr:
    x = ListNode(i)
    x = x.next

但现在x将变成None。由于没有其他要跟踪的内容,您无法打印元素。

您可以通过在循环之间打印x.val的值来验证此操作:

arr = [1,4,5]
for i in arr:
    x = ListNode(i)
    print(x.val)
    x = x.next

输出:

1
4
5

只有这一个类。 - Gaurang Shah

0

您可以在构造函数中添加一个next参数:

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

head = None
for x in [5, 1, 7, 96]:
    head = ListNode(x, next=head)

# Linked list looks like:
# (96) -> ( 7) -> ( 1) -> ( 5) -> None

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接