class Node:
def __init__(self):
self.data = None # contains the data
self.next = None # contains the reference to the next node
class linked_list:
def __init__(self):
self.cur_node = None
self.counter = 0
def add_node(self, data):
new_node = Node() # create a new node
new_node.data = data
new_node.next = self.cur_node # link the new node to the' previous' node.
self.cur_node = new_node # set the current node to the new one.
def list_print(self):
node = self.cur_node # cant point to ll!
while node:
print node.data
node = node.next
ll = linked_list()
ll.add_node(1)
ll.add_node(2)
ll.add_node(3)
ll.list_print()
之后我调用了成员函数add_node()三次。
但是当我调用函数list_print时,它会打印3-> 2> 1.
答案 0 :(得分:0)
在add_note方法中,您在声明最后一个之前将new_node.next =声明为self.cur_node,但是,这是不必要的。评论那条线!我添加了一个打印来检查该方法中的进度
class Node:
def __init__(self):
self.data = None # contains the data
self.next = None # contains the reference to the next node
class linked_list:
def __init__(self):
self.cur_node = None
self.counter = 0
def add_node(self, data):
new_node = Node() # create a new node
new_node.data = data
#new_node.next = self.cur_node # link the new node to the' previous' node.
print(self.cur_node)
self.cur_node = new_node # set the current node to the new one.
def list_print(self):
node = self.cur_node # cant point to ll!
while node:
print node.data
node = node.next
ll = linked_list()
ll.add_node(1)
ll.add_node(2)
ll.add_node(3)
ll.list_print()