我必须在堆栈中编写一个链表,这意味着我可以删除顶部的数字并从堆栈的顶端推送一个数字。不幸的是我的pop()方法FUNC不工作,我希望你能帮助我:从链表中删除一个节点(堆栈)
# ---------------init--------------
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
# ---------------is_empty--------------
def is_empty(self):
if self.cur_node == None:
print ("list is empty")
else:
print ("List = ")
ll.list_print()
# ---------------is_full--------------
# ---------------push--------------
def push(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.
# ---------------pop--------------
def pop(self):
print(node)
node = self.cur_node
while node:
if node.next == None:
node = None
break
else:
node=node.next
# ---------------print--------------
def list_print(self):
...
ll = linked_list()
ll.is_empty()
ll.push(1)
ll.push(3)
ll.push(2)
ll.is_empty()
ll.pop()
ll.list_print()
流行之前,电流输出()是
2
3
1
pop()方法之后,它应该是
3
1
我不知道python,但显然在你的'pop'中,你不会改变'self.cur_node',但只需按照堆栈的底部。刚刚使用'self.cur_node = self.cur_node.next'怎么样? – Codor 2015-01-09 20:12:36
@Codor我的教授给了我一个写函数is_full()的练习。在我看来,不可能找到一个完整的链表,因为你总是可以创建一个“新节点”。我猜,这是他的错......你觉得呢? – WirJun 2015-01-09 20:20:46
@Codor没错,就这么简单。 – augurar 2015-01-09 21:12:06