2014-11-06 3 views
0

У меня есть следующая реализация Linked List. Существует проблема с функцией printlist(). Цикл while превращает ошибку в отсутствие атрибута next для self. Есть ли лучший способ написать эту функцию? Спасибо!!!Печать Связанный список

class Node: 
    def __init__(self, data, next=None): 
    self.data=data 
    def _insert(self, data): 
    self.next=Node(data)  
    def _find(self, data): 
    if self.data==data: 
     return self 
    if self.next is None: 
     return None 
    while self.next is not None: 
     if self.next.data==data: 
     return self.next 
    return None 
    def _delete(self, data): 
    if self.next.data == data: 
     temp=self.next 
     self.next =self.next.next 
     temp=None 
    def _printtree(self): 
    while self: 
     print self.data, 
     self=self.next 
class LinkedList: 
    def __init__(self): 
    self.head=None 
    def insert(self, data): 
    if self.head: 
     self.head._insert(data) 
    else: 
     self.head=Node(data) 
    def find(self, data): 
    if self.head.data==data: 
     return self.head 
    return self.head._find(data) 

    def delete(self, data): 
    if self.head.data==data: 
     head=None 
     return 
    self.head._delete(data) 
    def printtree(self): 
    self.head._printtree() 
+0

Как вы это называете? Где полная трассировка? Что вы пробовали до сих пор, чтобы исправить это? – jonrsharpe

+1

Разве у вас нет 'self.next = next' в методе' Node .__ init__'? – khelwood

+0

Почему бы не использовать __str__ вместо _printtree и printtree? –

ответ

0
  1. добавить следующий атрибут ини метод узла
  2. вы должны определить printtree из LinkedList таким образом:

    Защиту printree (само):

    current_node = self.head 
    print current_node.data 
    while current_node.next is not None: 
        print current_node.next.data 
        current_node = current_node.next 
    

добавление a Ред. метод сделает y наш код лучше

Смежные вопросы