用兩個(gè)棧實(shí)現(xiàn)隊(duì)列驹溃,實(shí)現(xiàn)入隊(duì)和出隊(duì)方法
代碼:
class Queue(object):
def __init__(self):
self.stack1 = []
self.stack2 = []
#入隊(duì)
def enqueue(self,element):
if self.stack1:
self.stack1.append(element)
else:
while self.stack2:
self.stack1.append(self.stack2.pop())
self.stack1.append(element)
#出隊(duì)
def dequeue (self):
if self.stack2:
return self.stack2.pop()
elif self.stack1:
while self.stack1:
self.stack2.append(self.stack1.pop())
return self.stack2.pop()
else:
return None
if __name__=='__main__':
queue = Queue()
queue.enqueue('9')
queue.enqueue('10')
queue.enqueue('6')
queue.enqueue('2')
print queue.dequeue()
print queue.dequeue()
print queue.dequeue()
print queue.dequeue()
運(yùn)行結(jié)果為:
9
10
6
2
思路:
入隊(duì)時(shí),先判斷s1是否為空,如不為空蟆肆,說明所有元素都在s1,此時(shí)將入隊(duì)元素直接壓入s1号醉;如為空画饥,要將s2的元素逐個(gè)“倒回”s1,再壓入入隊(duì)元素漆腌。
出隊(duì)時(shí)贼邓,先判斷s2是否為空,如不為空闷尿,直接彈出s2的頂元素并出隊(duì)塑径;如為空,將s1的元素逐個(gè)“倒入”s2填具,把最后一個(gè)元素彈出并出隊(duì)统舀。