image.png
解法一:最简单的思路,stack1是我们的队列,stack2作为辅助, push时直接对stack1操作,pop时,先把左右的移到stack2,然后pop最上面的,然后再移回到s1
# -*- 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):
for i in range(len(self.stack1)):
self.stack2.append(self.stack1.pop())
ret = self.stack2.pop()
for i in range(len(self.stack2)):
self.stack1.append(self.stack2.pop())
return ret
# return xx
解法二:
是书上的思路,stack1和stack2 共同组成了我们的队列,push针对s1,pop时,如果s1不为空,则直接pop,如果s2为空,则将s1的移到s2. ,再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 len(self.stack2):
return self.stack2.pop()
else:
for i in range(len(self.stack1)):
self.stack2.append(self.stack1.pop())
return self.stack2.pop()
# return xx
c++解法:
stack1和stack2共同维护一个队列,push的话只在stack1中,当遇到一次pop操作时,如果stack2是空的,那么将是移到s2中,否则s2有的话,最上面的就是要返回的,因为是之前的最早的。
class Solution
{
public:
void push(int node) {
stack1.push(node);
}
int pop() {
if(stack2.size()){
int res = stack2.top();
stack2.pop();
return res;
}
else{
while(stack1.size() > 1){
int x = stack1.top();
stack1.pop();
stack2.push(x);
}
int res = stack1.top();
stack1.pop();
return res;
}
}
private:
stack<int> stack1;
stack<int> stack2;
};