232.用栈实现队列
题目链接:232.用栈实现队列
思路:push操作直接把数据放入输入栈中,pop操作需要判断输出栈是否为空,如果输出栈为空就将输入栈中的数据全部存入输出栈中(输入栈不为空),再从栈中弹出数据。如果输出栈不为空,就直接从输出栈弹出数据。
class MyQueue {
Stack<Integer> stackin;
Stack<Integer> stackout;
public MyQueue() {
stackin = new Stack<>();
stackout = new Stack<>();
}
public void push(int x) {
stackin.push(x);
}
public int pop() {
dummpstackin();
return stackout.pop();
}
public int peek() {
dummpstackin();
return stackout.peek();
}
public boolean empty() {
return stackin.isEmpty()&&stackout.isEmpty();
}
private void dummpstackin(){
if(stackout.empty()){
while(!stackin.empty()){
stackout.push(stackin.pop());
}
}
}
}
225.用队列实现栈
题目链接:225.用队列实现栈
思路:将元素传入que1中,如果que2为空交换que1与que2。如果que2不为空,循环将que2的值弹出后存入que1,交换que1和que2。
class MyStack {
Queue<Integer> queue1;
Queue<Integer> queue2;
public MyStack() {
queue1 = new LinkedList<>();
queue2 = new LinkedList<>();
}
public void push(int x) {
queue1.offer(x);
while(!queue2.isEmpty()){
queue1.offer(queue2.poll());
}
Queue temp = queue1;
queue1 = queue2;
queue2 = temp;
}
public int pop() {
return queue2.poll();
}
public int top() {
return queue2.peek();
}
public boolean empty() {
return queue2.isEmpty();
}
}