Python Forum

Full Version: set a new object node in a linked list via reference
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello,

I have written a script to create a circular list. The problem is that, when I add a node to the list using the push function, it is not actually added. I guess this is a problem of assigning the value via reference. Is there a way of doing this without returning the list from the function push? It looks like that the problem is in the line current_pointer = new_node. Here is the code

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

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

  def push (self, data):
    new_node = Node(data)

    if self.head == None:
      self.head = new_node
    else:
      current_pointer = self.head
      while current_pointer != None:
        current_pointer = current_pointer.next
      current_pointer = new_node
      

  def printCircularLinkedList(self):
    current_head = self.head
    while current_head != None:
      print("printing:", current_head.data)
      current_head = current_head.next


cllist = CircularLinkedList()

# Created linked list will be 11->2->56->12 
cllist.push(12) 
cllist.push(56) 
cllist.push(2) 
cllist.push(11) 
cllist.printCircularLinkedList() 
I don't see where you're ever setting a value for next.
After first push, next = None
I think line 17 should be:
current_pointer = self.head.next
Got it. This is how it should be implemented:

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