python列表当堆栈
First of all, we must aware with the Stack - the stack is a linear data structure that works on LIFO mechanism i.e. Last In First Out (that means Last inserted item will be removed (popped) first).
首先,我们必须了解堆栈 - 堆栈是一种线性数据结构,适用于LIFO机制,即后进先出 (这意味着最后插入的项将被首先移除(弹出))。
Thus, to implement a stack, basically we have to do two things:
因此,要实现堆栈,基本上我们必须做两件事:
Inserting (PUSH) elements at the end of the list
在列表末尾插入(PUSH)元素
Removing (POP) elements from the end of the list
从列表末尾删除(POP)元素
i.e. both operations should be done from one end.
即两种操作都应从一端完成。
In Python, we can implement a stack by using list methods as they have the capability to insert or remove/pop elements from the end of the list.
在Python中,我们可以使用列表方法来实现堆栈,因为它们具有从列表末尾插入或删除/弹出元素的功能。
Method that will be used:
将使用的方法:
append(x) : Appends x at the end of the list
追加(X):X附加在列表的末尾
pop() : Removes last elements of the list
pop() :删除列表的最后一个元素
程序使用列表堆栈 (Program to use list stack)
# Python Example: use list as stack
# Declare a list named as "stack"
stack = [10, 20, 30]
print ("stack elements: ");
print (stack)
# push operation
stack.append(40)
stack.append(50)
print ("Stack elements after push opration...");
print (stack)
# push operation
print (stack.pop (), " is removed/popped...")
print (stack.pop (), " is removed/popped...")
print (stack.pop (), " is removed/popped...")
print ("Stack elements after pop operation...");
print (stack)
Output
输出量
stack elements:
[10, 20, 30]
Stack elements after push opration...
[10, 20, 30, 40, 50]
50 is removed/popped...
40 is removed/popped...
30 is removed/popped...
Stack elements after pop operation...
[10, 20]
翻译自: https://www.includehelp.com/python/using-lists-as-stack-in-python.aspx
python列表当堆栈
523

被折叠的 条评论
为什么被折叠?



