创建链接的Lis

2024-04-20 13:45:24 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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)

Tags: 代码ioimportselfnonenodedatastring
2条回答

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

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    

您只保留对链(head.next)的的引用,因此是的,您只能显示最后一个元素。你知道吗

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

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

相关问题 更多 >