题目:用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。
牛客网:链接
LeetCode:LeetCode232:Implement Queue using Stacks
要多思考,不像想象中那样简单。
需要两个栈Stack1和Stack2,push的时候直接push进Stack1。pop需要判断Stack1和Stack2中元素的情况,Stack2有值,直接从Stack2 pop,如果没有值,就把Stack1中的元素加入Stack2中,再进行pop。
# -*- coding:utf-8 -*-
class Solution:
def __init__(self):
self.stack1 = []
self.stack2 = []
def push(self, node):
# write code here
self.stack1.append(node)
def pop(self):
if not self.stack2:
while self.stack1:
self.stack2.append(self.stack1.pop())
return self.stack2.pop()
用两个队列实现栈
我们先往栈内压入一个元素a。由于两个队列现在都是空,我们可以选择把a插入两个队列中的任一个。我们不妨把a插入queue1。接下来继续网栈内压入b,c两个元素。我们把它们都插入queue1。这个时候 queue1包含3个元素a,b,c其中a位于队列的头部,c位于队列的尾部。
现在我们考虑从栈内弹出一个元素。根据栈的后入先出的原则,最后被压入栈的c应该最先被弹出。由于c位于queue1的尾部,而我们每次只能从队列的头部删除元素,因此我们可以从queue1中依次删除a/b并插入到queue2中,再从queue1中删除c。这就相当于从栈中弹出元素c了。我们可以用同样的方法从栈内弹出元素b。
接下来我们考虑从栈内压入一个元素d.此时queue1已经有了一个元素,我们就把d插入到queue1的尾部。如果我们再从栈内弹出一个元素,此时被弹出的应该是最后被压入的d.由于d位于queue1的尾部,我们只能先从头部删除 queue1的元素并插入到queue2,直到queue1中遇到d再直接把它删除。如果所示:
# -*- coding:UTF-8 -*-
'''
两个队列实现栈
'''
class Solution:
def __init__(self):
self.deque1 = []
self.deque2 = []
def push(self, x):
if not self.deque2:
self.deque1.append(x)
else:
self.deque2.append(x)
def pop(self):
if not self.deque1 and not self.deque2:
return False
if self.deque1:
length = len(self.deque1)
for i in range(length-1):
self.deque2.append(self.deque1.pop(0))
return self.deque1.pop(0)
else:
length = len(self.deque2)
for i in range(length-1):
self.deque1.append(self.deque2.pop(0))
return self.deque2.pop(0)
P = Solution()
P.push(10)
P.push(11)
P.push(12)
print(P.pop())
P.push(13)
print(P.pop())
print(P.pop())
print(P.pop())
print(P.pop())