生活随笔
收集整理的這篇文章主要介紹了
Python:两个队列实现栈,两个栈实现队列
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
1、兩個棧實現一個隊列
有三種思路:
-
思路一:將stack1作為存儲空間,將stack2作為臨時緩沖區,入隊時,直接壓入stac1,出隊時,將stack1中的元素依次出棧壓入stack2中,再將stack2的棧頂元素彈出,最后將stack2中的元素再倒回給stack1
-
思路二:入隊時,判斷stack1是否為空,如果stack1為空,則將stack2中的所有元素都倒入stack1中,再將元素直接壓入stack1,否則,直接壓入stack1中
出隊時,判斷stack2是否為空,如果stack2為空,則將stack1中的元素倒入stack2中,在將stack2的棧頂元素彈出,否則,直接彈出stack2的棧頂元素
-
思路三:入隊時,直接壓入stack1中出隊時,判斷stack2是否為空,如果stack2為空,則將stack1中的元素倒入stack2中,否則直接彈出stack2中的元素
思路一與思路二相比,如果是連續出棧操作或連續進棧操作,思路二比思路一好很多。思路三最好代碼如下。
'''
遇到問題沒人解答?小編創建了一個Python學習交流QQ群:531509025
尋找有志同道合的小伙伴,互幫互助,群里還有不錯的視頻學習教程和PDF電子書!
'''
class QueueWithTwoStack(object):def __init__(self
):self
._stack1
= []self
._stack2
= []def pop(self
):if self
._stack2
:return self
._stack2
.pop
()elif not self
._stack1
:return Noneelse:while self
._stack1
:self
._stack2
.append
(self
._stack1
.pop
())return self
._stack2
.pop
()def push(self
, x
):self
._stack1
.append
(x
)a
= QueueWithTwoStack
()for i
in range(5):a
.push
(i
)
for i
in range(5):print(a
.pop
())
2、兩個隊列實現一個棧
將queue1用作進棧出棧,queue2作為一個中轉站
入棧時,直接壓入queue1中
出棧時,先將queue1中的元素除最后一個元素外依次出隊列,并壓入隊列queue2中,將留在queue1中的最后一個元素出隊列即為出棧元素,最后還要把queue2中的元素再次壓入queue1中
圖示:
實現代碼如下:
class StackWithTwoQueue(object):def __init__(self
):self
._queue1
= [] self
._queue2
= []def push(self
, x
):self
._queue1
.append
(x
)def pop(self
):if not self
._queue1
:return Nonewhile self
._queue1
:if self
._queue1
.__len__
() == 1:m
= self
._queue1
.pop
()breakelse:self
._queue2
.append
(self
._queue1
.pop
(0))while self
._queue2
:self
._queue1
.append
(self
._queue2
.pop
(0))return mb
= StackWithTwoQueue
()
n
= 3for i
in range(n
):b
.push
(i
)
for i
in range(n
):print(b
.pop
())
總結
以上是生活随笔為你收集整理的Python:两个队列实现栈,两个栈实现队列的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。