题目描述
用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。
java
1.解法1:堆栈的特性是"先进后出",队列的特性是"先进先出",我们可以利用该特性来实现。
import java.util.Stack;
public class Solution {
Stack<Integer> stack1 = new Stack<Integer>();
Stack<Integer> stack2 = new Stack<Integer>();
public void push(int node) {
//只要有入队请求,都将元素push到栈1中
stack1.push(node);
}
public int pop() {
//只有当栈2中没有元素才进行入栈操作
if (stack2.isEmpty()) {
if (stack1.isEmpty()) {
throw new IndexOutOfBoundsException("dequeue dont have element");
}
//直到栈1中没有元素出栈
while (!stack1.isEmpty()) {
stack2.push(stack1.pop());
}
}
return stack2.pop();
}
}
c++
解法1:与java不同,获取栈顶需要使用top函数,pop函数只是出栈,并没有返回栈顶的值,其为void的类型。
class Solution
{
public:
void push(int node) {
stack1.push(node);
}
int pop() {
if (stack2.empty()) {
if (stack1.empty()) {
throw "queue dont have element";
}
while (!stack1.empty()) {
stack2.push(stack1.top());
stack1.pop();
}
}
int target = stack2.top();
stack2.pop();
return target;
}
private:
stack<int> stack1;
stack<int> stack2;
};