Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 创建链接列表_Python_Python 3.x - Fatal编程技术网

Python 创建链接列表

Python 创建链接列表,python,python-3.x,Python,Python 3.x,我正在尝试创建一个链接列表。但是,下面的代码只打印列表的最后一个元素。我的代码中有错误吗?我认为问题在于“插入”方法。但我不知道为什么 import sys import io string = """4 2 3 4 1""" sys.stdin = io.StringIO(string) class Node: def __init__(self, data): self.data = data self.next = None class

我正在尝试创建一个链接列表。但是,下面的代码只打印列表的最后一个元素。我的代码中有错误吗?我认为问题在于“插入”方法。但我不知道为什么

import sys
import io


string = """4
2
3
4
1"""
sys.stdin = io.StringIO(string)


class Node:
    def __init__(self, data):
        self.data = data
        self.next = None


class Solution:
    def display(self, head):
        current = head
        while current:
            print(current.data, end=' ')
            current = current.next

    # TODO: Code only prints the last element of data
    def insert(self, head, data):
        if head == None:
            head = Node(data)
            return head
        else:
            head.next = Node(data)
            return head.next


mylist = Solution()
T = int(input())
head = None
for i in range(T):
    data = int(input())
    head = mylist.insert(head, data)

mylist.display(head)

您只保留对链末端(
head.next
)的引用,因此是的,您只能显示最后一个元素

您需要保留对第一个元素(真实头部)的引用:


您只保留对链末端(
head.next
)的引用,因此是的,您只能显示最后一个元素

您需要保留对第一个元素(真实头部)的引用:


问题是你失去了对列表头的引用。您必须保留标题,并在列表末尾插入新项

def insert(self,head,data): 
    if head == None:
        head = Node(data)
    else:
        current = head
        while current.next != None:
            current = current.next
        current.next = Node(data)
    return head    

问题是你失去了对列表头的引用。您必须保留标题,并在列表末尾插入新项

def insert(self,head,data): 
    if head == None:
        head = Node(data)
    else:
        current = head
        while current.next != None:
            current = current.next
        current.next = Node(data)
    return head