目录
- 题目
- 1- 思路
- 2- 实现
- ⭐232. 用栈实现队列——题解思路
- 3- ACM 实现
题目
- 原题连接:232. 用栈实现队列
1- 思路
思路
- ① 用两个栈来实现队列,一个
in 入栈
和一个out 出栈
- ② push 入队:入栈逻辑:即将元素加入到
in 栈
里即可 - ③ pop 出队:出栈逻辑,先将
in栈
内容 依次弹出,加入到out栈
中 - ④ peek 取顶:先 pop 再 push,返回弹出的元素
2- 实现
⭐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() {
dumpStackIn();
return stackOut.pop();
}
public int peek() {
dumpStackIn();
return stackOut.peek();
}
public boolean empty() {
return stackIn.isEmpty() && stackOut.isEmpty();
}
public void dumpStackIn(){
if(!stackOut.isEmpty()) return;
while(!stackIn.isEmpty()){
stackOut.push(stackIn.pop());
}
}
}
3- ACM 实现
public 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(){
dumpIn();
return stackOut.pop();
}
public int peek(){
dumpIn();
return stackOut.peek();
}
public boolean empty(){
return stackIn.isEmpty()&&stackOut.isEmpty();
}
public void dumpIn(){
if(!stackOut.isEmpty()) return;
while(!stackIn.isEmpty()){
stackOut.push(stackIn.pop());
}
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
MyQueue queue = new MyQueue();
while (sc.hasNext()) {
String command = sc.next();
switch (command) {
case "MyQueue":
queue = new MyQueue();
case "push":
if (sc.hasNextInt()) {
int x = sc.nextInt();
queue.push(x);
}
break;
case "pop":
System.out.println(queue.pop());
break;
case "peek":
System.out.println(queue.peek());
break;
case "empty":
System.out.println(queue.empty());
break;
}
}
sc.close();
}
}