Basil Basil - 1 year ago 67
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): = data
self.next_node = next_node

def get_data(self):

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

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
object. What am I doing wrong?

Answer Source

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download