Basil Basil - 24 days ago 10
Python Question

Issue with linked list implementation

While implementing linked list in Python I faced a little conundrum. Here's my code

class Node(object):

def __init__(self, data=None, next_node=None):
self.data = data
self.next_node = next_node

def get_data(self):
return self.data

def get_next(self):
return self.next_node

def set_next(self, new_next):
self.next_node = new_next


class LinkedList(object):

def __init__(self, head=None):
self.head = head

def insert(self, data):
new_node = Node(data)
new_node.set_next(self.head)
self.head = new_node


n = Node(1)
L = LinkedList()
print('data in node:', n.get_data())
print('next node:', n.get_next())
print('head:', L.head)

L.insert(n)
print('head after insertion:', L.head)
print('try to get data stored in head:', L.head.get_data())


The problem is illustrated by the last line: when I'm trying to get the data stored in head node, instead of that data I get
Node
object. What am I doing wrong?

Answer

The problem is here

   new_node = Node(data)

You're treating data as if it is a value while you're passing a Node(1) instead of simply 1