代码随想录算法训练营
今日任务
理论基础 ,232.用栈实现队列 ,225. 用队列实现栈
理论基础
https://programmercarl.com/%E6%A0%88%E4%B8%8E%E9%98%9F%E5%88%97%E7%90%86%E8%AE%BA%E5%9F%BA%E7%A1%80.html
232.用栈实现队列
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() {
while(!stackIn.isEmpty()){
Integer num = stackIn.pop();
stackOut.push(num);
}
Integer pop = stackOut.pop();
while(!stackOut.isEmpty()){
Integer num = stackOut.pop();
stackIn.push(num);
}
return pop;
}
public int peek() {
while(!stackIn.isEmpty()){
Integer num = stackIn.pop();
stackOut.push(num);
}
Integer peek = stackOut.peek();
while(!stackOut.isEmpty()){
Integer num = stackOut.pop();
stackIn.push(num);
}
return peek;
}
public boolean empty() {
if(stackIn.isEmpty()&&stackOut.isEmpty()){
return true;
}
return false;
}
}
/**
* Your MyQueue object will be instantiated and called as such:
* MyQueue obj = new MyQueue();
* obj.push(x);
* int param_2 = obj.pop();
* int param_3 = obj.peek();
* boolean param_4 = obj.empty();
*/
225. 用队列实现栈
class MyStack {
Queue<Integer> queueIn;
Queue<Integer> queueOut;
public MyStack() {
queueIn=new LinkedList<>();
queueOut=new LinkedList<>();
}
//入队offer
//出队poll
public void push(int x) {
queueIn.offer(x);
}
public int pop() {
//出栈
while(queueIn.size()>1){
Integer num = queueIn.poll();
queueOut.offer(num);
}
Integer poll = queueIn.poll();
while(!queueOut.isEmpty()){
Integer num = queueOut.poll();
queueIn.offer(num);
}
return poll;
}
public int top() {
while(queueIn.size()>1){
Integer num = queueIn.poll();
queueOut.offer(num);
}
Integer peek = queueIn.peek();
queueIn.poll();
queueOut.offer(peek);
while(!queueOut.isEmpty()){
Integer num = queueOut.poll();
queueIn.offer(num);
}
return peek;
}
public boolean empty() {
if(queueIn.isEmpty()&&queueOut.isEmpty()){
return true;
}
return false;
}
}
/**
* 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();
*/