Sarah Markers
Sarah Markers

Reputation: 61

Printing Linked List

I have the following Linked List implementation. There is a problem with the printlist() function. The while loop is turning an error that there is no attribute next for self. Is there a better way to write this function? Thank you!!!

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()  

Upvotes: 0

Views: 823

Answers (1)

Kokoman
Kokoman

Reputation: 86

  1. add next attribute to Node's ini method
  2. you should define printtree of LinkedList this way:

    def printree(self):

    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
    

adding a repr method will make your code nicer

Upvotes: 1

Related Questions