我想编写一个类,它使用来自栈(带单链表)的Push和Pop。我不知道如何编写推送和弹出功能。我真的需要一个用Python编写的简单示例,并具有以下功能。Python中的单链表,如何编写pop和push?
Push
Pop
ifEmpty
我想编写一个类,它使用来自栈(带单链表)的Push和Pop。我不知道如何编写推送和弹出功能。我真的需要一个用Python编写的简单示例,并具有以下功能。Python中的单链表,如何编写pop和push?
Push
Pop
ifEmpty
从the docs那迪诺福链接到:
的列表方法使它很容易 使用列表作为堆栈,其中最后添加的 元素是第一要素 检索( “后进先出”)。到 添加一个项目到堆栈的顶部, 使用
append()
。要从 检索堆栈顶部的项目,请使用pop()
而不显示索引。对于 例如:
>>> stack = [3, 4, 5]
>>> stack.append(6)
>>> stack.append(7)
>>> stack
[3, 4, 5, 6, 7]
>>> stack.pop()
7
>>> stack
[3, 4, 5, 6]
>>> stack.pop()
6
>>> stack.pop()
5
>>> stack
[3, 4]
最后,为了check if a list is empty:
>>> my_list = []
>>> not my_list
True
这里是最简单的Stack类:
class stack(list):
def push(self,item):
self.append(item)
def isEmpty(self):
return not self
>>> a = stack()
>>> a.push(1)
>> a.isEmpty()
False
>>> a.pop()
1
>>> a.isEmpty()
True
http://stackoverflow.com/questions/ 280243/python-linked-list Google上的第二个结果。 – Vince
为什么使用链表? Python的内置列表非常适合这一点。 – Thomas
http://docs.python.org/tutorial/datastructures.html#using-lists-as-stacks –