牛客网上有一道很nt的题目,用两个栈实现队列,你直接用队列不好吗?还耗内存,真的是脱裤子放屁,但是骂归骂,题目还是要做的。
用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。
我们可以用stack1进栈,stack2出栈。这样就可以让先进先出的顺序变成先进后出。如果stack2为空的话,stack1进栈元素进stack2 。stack2再出栈就可以了
import java.util.Stack;
public class Solution {
Stack<Integer> stack1 = new Stack<Integer>();
Stack<Integer> stack2 = new Stack<Integer>();
public void push(int node) {
//放就往栈1里面放
stack1.push(node);
}
public int pop() {
//拿就从栈2拿,如果没有就栈1 的入栈
if(!stack2.isEmpty()){
return stack2.pop();
}else{
while(!stack1.isEmpty()){
stack2.push(stack1.pop());
}
return stack2.pop();
}
}
}
我记得还有一道也是nt的题目,用两个队列实现一个栈
我都无语了,吃饱了没事干吗?
思路就是:放元素的时候,往空的哪一个队列放,放完之后,让另外一个队列的元素进队。每次都这样操作
class MyStack {
Queue<Integer> q1,q2;
/** Initialize your data structure here. */
public MyStack() {
q1 = new LinkedList<>();
q2 = new LinkedList<>();
}
/** Push element x onto stack. */
public void push(int x) {
if(q1.isEmpty()){
q1.offer(x);
}else{
//往q2里放
q2.offer(x);
//吧q1的放到q2去
while(!q1.isEmpty()){
q2.offer(q1.poll());
}
//现在q1已经没了
//缓过来,让q2为空
Queue temp = q1;
q1 = q2;
q2 = temp;
}
}
/** Removes the element on top of the stack and returns that element. */
public int pop() {
return q1.poll();
}
/** Get the top element. */
public int top() {
return q1.peek();
}
/** Returns whether the stack is empty. */
public boolean empty() {
return q1.isEmpty();
}
}
/**
* Your MyStack object will be instantiated and called as such:
* MyStack obj = new MyStack();
* obj.push(x);
* int param_2 = obj.pop();
* int param_3 = obj.top();
* boolean param_4 = obj.empty();
*/