題目描述
用兩個(gè)棧來(lái)實(shí)現(xiàn)一個(gè)隊(duì)列,完成隊(duì)列的Push和Pop操作。 隊(duì)列中的元素為int類型。
基本思想
兩個(gè)棧s1和s2,入隊(duì)就將元素入s1棧,出隊(duì)時(shí),如果s2中為空,將s1里全部元素彈出壓入s2,再?gòu)棾觯蝗绻鹲2中不為空,則彈出,直到s2為空
Python
class Solution:
? ? def __init__(self):
? ? ? ? self.s1 = []
? ? ? ? self.s2 = []
? ? def push(self, node):
? ? ? ? # write code here
? ? ? ? self.s1.append(node)
? ? def pop(self):
? ? ? ? # return
? ? ? ? if self.s2: #s2不為空
? ? ? ? ? ? return self.s2.pop()
? ? ? ? elif not self.s1: #s1為空
? ? ? ? ? ? return None
? ? ? ? else:
? ? ? ? ? ? while self.s1: # s2為空,s1不為空
? ? ? ? ? ? ? ? self.s2.append(self.s1.pop())
? ? ? ? ? ? return self.s2.pop()