如何在python中创建链接列表 [英] how do create a linked list in python

查看:57
本文介绍了如何在python中创建链接列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试解决python中的链表编码挑战.而且我只给了以下课程来创建链接列表

I am trying to solve a linked list coding challenge in python. And I have given only following class to create a linked list

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

我可以创建一个类似这样的链接列表

I can create a linked list something like this

x = ListNode(1)
x.next = ListNode(4)
x.next.next = ListNode(5)

但是,我如何迭代创建(在for循环内)

however, How do I create iterativly (inside a for loop)

推荐答案

您需要两个指针"来记住列表的开头和结尾.磁头初始化一次.您最终将使用它来访问整个列表.每次添加另一个节点时,尾部都会改变:

You need two "pointers" that memorize the head and the tail of your list. The head is initialized once. You will eventually use it to access the whole list. The tail changes every time you add another node:

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

这篇关于如何在python中创建链接列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆