232. 用栈实现队列
https://leetcode.cn/problems/implement-queue-using-stacks/description/
class MyQueue {
Stack<Integer> stackIn;
Stack<Integer> stackOut;
public MyQueue() {
stackIn = new Stack<>();
stackOut = new Stack<>();
}
public void push(int x){
stackIn.add(x);
}
public int pop(){
dumpstackIn();
return stackOut.pop();
}
public int peek(){
dumpstackIn();
return stackOut.peek();
}
public boolean empty(){
return stackOut.isEmpty() && stackIn.isEmpty();
}
public void dumpstackIn(){
if (stackOut.isEmpty()){
while (!stackIn.isEmpty()){
stackOut.push(stackIn.pop());
}
}
}
}
总结:两个栈,栈顶放一起,栈顶向两边,重点就是out栈空了的时候从in栈拿元素放out栈里
225. 用队列实现栈
https://leetcode.cn/problems/implement-stack-using-queues/description/
Queue<Integer> queue;
public MyStack() {
queue = new LinkedList<>();
}
//每 offer 一个数(A)进来,都重新排列,把这个数(A)放到队列的队首
public void push(int x) {
queue.offer(x);
int size = queue.size();
//移动除了 A 的其它数
while (size-- > 1)
queue.offer(queue.poll());
}
public int pop() {
return queue.poll();
}
public int top() {
return queue.peek();
}
public boolean empty() {
return queue.isEmpty();
}
总结:每次插入元素之后都让他去队首(把队列中的元素重新排列)
标签:第十天,队列,stackIn,随想录,queue,int,stackOut,public From: https://www.cnblogs.com/jeasonGo/p/18075029