Skip to content
Miliya's Expedition
Go back

【題目】使用堆疊模擬佇列

Updated:

題目

https://leetcode.com/problems/implement-queue-using-stacks Implement a first in first out (FIFO) queue using only two stacks. The implemented queue should support all the functions of a normal queue (push, peek, pop, and empty).

Implement the MyQueue class:

Notes:


Understand

使用兩個堆疊Stack模擬佇列Queue。兩者的差異在於

Case說明
空 Queue 呼叫 empty()應回傳 true
只 push 一個元素後 pop()Queue 應變空
交錯 push / pop順序仍需正確 FIFO

Match

題目要考堆疊的特性,以及如何轉換資料結構 佇列是先進先出,而堆疊是先進後出,所以使用兩個堆疊,一個堆疊A負責儲存資料,另一個堆疊B負責取出資料,將資料從A倒入B就剛好會讓先進入堆疊A的資料從堆疊B先出去

Stack A(push用)    Stack B(pop用)
  [1, 2, 3]    →倒入→    [3, 2, 1]
  top = 3                top = 1  ← 正好是 Queue 的 front!

Plan

設計兩個堆疊

Implement

class MyQueue

	def __init__():
		self.stack_in = []
		self.stack_out = []
		
	def push(self, x: int) -> None:
		self.stack_in.append(x)
		
	def migrate(self) -> None:
		if not self.stack_out:
			while self.stack_in:
				self.stack_out.append(slef.stack_in.pop())

    def pop(self) -> int:
		slef.migrate()
		self.stack_out.pop()		

    def peek(self) -> int:
	    slef.migrate()
	    self.stack_out[-1]

    def empty(self) -> bool:
		return not self.stack_out and not self.stack_in	

Review

Happy Case 跑過程式:

push(1): stack_in=[1], stack_out=[] 
push(2): stack_in=[1,2], stack_out=[] 
push(3): stack_in=[1,2,3], stack_out=[]

peek(): _migrate() → stack_out=[3,2,1], 
stack_in=[] return stack_out[-1] = 1 ✅

Evaluate

操作時間複雜度說明
pushO(1)直接 append
pop均攤 O(1)每個元素最多被移動一次
peek均攤 O(1)同上
emptyO(1)只檢查長度

Share this post on:

Previous Post
【題目】找最大容積
Next Post
動態規劃Dynamic Programming