兩個隊列實現棧,兩個棧實現隊列


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中的元素
思路一與思路二相比,如果是連續出棧操作或連續進棧操作,思路二比思路一好很多。思路三最好代碼如下。

棧實現Q

 

# 兩個棧實現一個隊列
# 棧先近后
# 列表的append 和pop結合就是棧
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 None
        else:
            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中
圖示:

Q實現棧

實現代碼如下:

# 兩個隊列實現一個棧
# 隊列就是先進先出 使用列表的append() 和pop(0)實現
# 棧就是先進后出

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 None
        while self._queue1:
            if self._queue1.__len__() == 1:
                m = self._queue1.pop()
                break
            else:
                self._queue2.append(self._queue1.pop(0))
        while self._queue2:
            self._queue1.append(self._queue2.pop(0))
        return m


b = StackWithTwoQueue()
n = 3

for i in range(n):
    b.push(i)
for i in range(n):
    print(b.pop())


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM