python列表当堆栈_在Python中使用列表作为堆栈

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:

因此,要实现堆栈,基本上我们必须做两件事:

  1. Inserting (PUSH) elements at the end of the list

    在列表末尾插入(PUSH)元素

  2. 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:

将使用的方法:

  1. append(x) : Appends x at the end of the list

    追加(X):X附加在列表的末尾

  2. 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列表当堆栈

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值