链表实施问题

时间:2016-11-14 18:12:02

标签: python linked-list

在Python中实现链表时,我遇到了一个难题。这是我的代码

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

最后一行说明了这个问题:当我试图将数据存储在头节点中时,而不是那些数据,我获得了Node个对象。我做错了什么?

1 个答案:

答案 0 :(得分:3)

问题出在这里

   new_node = Node(data)

当您传递Node(1)而不仅仅是1

时,您将数据视为价值