题目描述
正如标题所述,你需要使用两个栈来实现队列的一些操作。
队列应支持push(element),pop() 和 top(),其中pop是弹出队列中的第一个(最前面的)元素。
pop和top方法都应该返回第一个元素的值。
样例1
输入:
push(1)
pop()
push(2)
push(3)
top()
pop()
输出:
1
2
2
样例2
输入:
push(1)
push(2)
push(2)
push(3)
push(4)
push(5)
push(6)
push(7)
push(1)
输出:
[]
解题思路
push加入到栈中
top即从A栈出到B栈,执行完之后,B栈push出栈顶元素,作为返回值,然后继续入站栈,最后B栈出,返回A栈。
pop即从A栈出到B栈,执行完之后,B栈push出栈顶元素,然后B栈依次出,返回A栈。
java题解
public class MyQueue {
private Stack<Integer> stack1;
private Stack<Integer> stack2;
public MyQueue() {
// do initialization if necessary
stack1 = new Stack<Integer>();
stack2 = new Stack<Integer>();
}
private void stack2ToStack1(){
while(! stack2.isEmpty()){
stack1.push(stack2.pop());
}
}
public void push(int element) {
// write your code here
stack2.push(element);
}
public int pop() {
// write your code here
if(stack1.empty() == true){
this.stack2ToStack1();
}
return stack1.pop();
}
public int top() {
// write your code here
if(stack1.empty() == true){
this.stack2ToStack1();
}
return stack1.peek();
}
}
C++题解
class MyQueue {
public:
stack<int> stack1;
stack<int> stack2;
MyQueue() {
}
void push(int element) {
stack1.push(element);
}
void adjust() {
if (stack2.empty()) {
while (!stack1.empty()) {
stack2.push(stack1.top());
stack1.pop();
}
}
}
int pop() {
adjust();
int temp = stack2.top();
stack2.pop();
return temp;
}
int top() {
adjust();
return stack2.top();
}
};
python题解
class MyQueue:
def __init__(self):
self.stack1 = []
self.stack2 = []
def adjust(self):
if len(self.stack2) == 0:
while len(self.stack1) != 0:
self.stack2.append(self.stack1.pop())
def push(self, element):
self.stack1.append(element)
def top(self):
self.adjust()
return self.stack2[len(self.stack2) - 1]
def pop(self):
self.adjust()
return self.stack2.pop()