创建链接列表

时间:2016-01-19 15:01:28

标签: 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 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)

2 个答案:

答案 0 :(得分:4)

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

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    

答案 1 :(得分:1)

您只保留对链的 end 的引用(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