文章目录
- 一、题目链接
- 二、解题思路
- 三、解题代码
一、题目链接
用栈实现队列
二、解题思路
三、解题代码
class MyQueue {
public Stack<Integer> stack1 ;
public Stack<Integer> stack2;
public MyQueue() {
stack1 = new Stack<>();
stack2 = new Stack<>();
}
public void push(int x) {
stack1.push(x);
}
public int pop() {
if (empty()){
return -1;
}
if(!stack2.empty()){
return stack2.pop();
}else{
int curSize = stack1.size();
while(curSize != 0){
stack2.push(stack1.pop());
curSize--;
}
return stack2.pop();
}
}
public int peek() {
if (empty()){
return -1;
}
if(!stack2.empty()){
return stack2.peek();
}else{
int curSize = stack1.size();
while(curSize != 0){
stack2.push(stack1.pop());
curSize--;
}
return stack2.peek();
}
}
public boolean empty() {
if(stack1.empty() && stack2.empty()){
return true;
}
return false;
}
}