0

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?

1
  • 2
    You insert a Node, then in the insert method you create a new Node from that Node. You want L.insert(1), not L.insert(Node(1)) Commented Nov 14, 2016 at 18:15

1 Answer 1

3

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.