首页 技术 正文
技术 2022年11月14日
0 收藏 460 点赞 4,381 浏览 1819 个字

栈与队列

1.栈(stacks)是一种只能通过访问其一端来实现数据存储与检索的线性数据结构,具有后进先出(last in first out,LIFO)的特征

2.队列(queue)是一种具有先进先出特征的线性数据结构,元素的增加只能在一端进行,元素的删除只能在另一端进行。能够增加元素的队列一端称为队尾,可以删除元素的队列一端则称为队首。

栈(stacks)

stack = [3, 4, 5]
stack.append(2)
stack.append(6)
print(stack)
stack.pop()
print(stack)
stack.pop()
print(stack)
[3, 4, 5, 2, 6]
[3, 4, 5, 2]
[3, 4, 5]

队列(queue)

from collections import deque
queue = deque(["Eric", "John", "Michael"])
print(queue)
queue.append("Terry") # Terry arrives
queue.append("Graham") # Graham arrives
print(queue)
queue.popleft() # The first to arrive now leaves
queue.popleft() # The second to arrive now leaves
deque(['Michael', 'Terry', 'Graham'])
print(queue)
deque(['Eric', 'John', 'Michael'])
deque(['Eric', 'John', 'Michael', 'Terry', 'Graham'])
deque(['Michael', 'Terry', 'Graham'])

使用队列实现栈

创建两个栈stack1和stack2,使用两个“先进后出”的栈实现一个“先进先出”的队列。

我们通过一个具体的例子分析往该队列插入和删除元素的过程。首先插入一个元素a,不妨先把它插入到stack1,此时stack1中的元素有{a},stack2为空。再压入两个元素b和c,还是插入到stack1中,此时stack1的元素有{a,b,c},其中c位于栈顶,而stack2仍然是空的。

这个时候我们试着从队列中删除一个元素。按照先入先出的规则,由于a比b、c先插入队列中,最先删除的元素应该是a。元素a存储在stack1中,但并不在栈顶,因此不能直接进行删除操作。注意stack2我们一直没有使用过,现在是让stack2发挥作用的时候了。如果我们把stack1中的元素逐个弹出压入stack2,元素在stack2中的顺序正好和原来在stack1中的顺序相反。因此经过3次弹出stack1和要入stack2操作之后,stack1为空,而stack2中的元素是{c,b,a},这个时候就可以弹出stack2的栈顶a了。此时的stack1为空,而stack2的元素为{b,a},其中b在栈顶。

因此我们的思路是:当stack2中不为空时,在stack2中的栈顶元素是最先进入队列的元素,可以弹出。如果stack2为空时,我们把stack1中的元素逐个弹出并压入stack2。由于先进入队列的元素被压倒stack1的栈底,经过弹出和压入之后就处于stack2的栈顶,有可以直接弹出。如果有新元素d插入,我们直接把它压入stack1即可。

class Solution:
def __init__(self):
self.stack1 = []
self.stack2 = []
self.result = []
def push(self, node):
# write code here
self.stack1.append(node)
self.result = self.stack1 + self.stack2
def pop(self):
# return xx
if len(self.stack2) == 0:
while self.stack1:
self.stack2.append(self.stack1.pop())
self.result = self.stack2
return self.stack2.pop()a = Solution()
a.push(1)
a.push(2)
a.push(3)
a.push(4)
print(a.result)
a.pop()
print(a.result)
a.pop()
print(a.result)
[1, 2, 3, 4]
[4, 3, 2]
[4, 3]
相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,494
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,908
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,740
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,495
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:8,133
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:5,297