Reputation:
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?
Upvotes: 0
Views: 41
Reputation: 3535
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
Upvotes: 3