2016-07-26 94 views
0

我很難理解如何正確修復插入節點函數。我沒有收到任何錯誤,但我也沒有顯示該列表。Python插入節點函數

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, 
      current = current.next 

    def insert(self, head, data): 
     self.head = head 
     new_node = Node(data) 
     if self.head is None: 
      self.head = new_node 
     else: 
      new_node.next = self.head 
      self.head = new_node 

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

u能解決您的壓痕在'while'循環? –

回答

0

您的插入()沒有返回任何東西。因此,如果您爲其分配返回值,那麼head將爲None。

0

我覺得這是你想要

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


class Solution: 
    def __init__(self): 
     self.head = None 

    def display(self): 
     current = self.head 
     while current: 
      print current.data, 
      current = current.next 

    def insert(self, data): 
     new_node = Node(data) 
     if self.head is None: 
      self.head = new_node 
     else: 
      new_node.next = self.head 
      self.head = new_node 


mylist = Solution() 
T = int(input()) 
for i in range(T): 
    data = int(input()) 
    mylist.insert(data) 
mylist.display() 
+0

對不起,由於這個挑戰的性質,我沒有在原始文章中提到,除了類Solution的插入功能之外,我無權編輯任何代碼。 – user2849274