栈:后进先出
入栈 a->b->c
出栈 c->b->a
队列:先进先出
思路:
栈和队列的区别,无非是栈是一头堵住的,队列是两头通的管道,
那我们把栈底堵住那头打通用来出栈不就行了
1、搞个栈stack1做队尾,用来入队
2、再搞个栈stack2把stack1数据压进去实现数据翻转
3、 入栈在stack1进行
出栈、查询则在stack2进行
4、注意每次出栈后将数据灌回stack1
如下图
代码实现:
package com.test.hlwyy;
import java.util.Stack;
public class MyQueue {
private Stack<Integer> stack1= new Stack<>();
private Stack<Integer> stack2= new Stack<>();
//两个栈之间倒数据
void turnStack(Stack<Integer> stack1, Stack<Integer> stack2) {
while(!stack1.isEmpty()){
stack2.push(stack1.peek());
stack1.pop();
}
}
public MyQueue() {}
//入栈
void push(int x) {
stack1.push(x);
}
//出队
int pop() {
//stack1数据倒给stack2
turnStack(stack1, stack2);
//获取stack2队头
int top = stack2.peek();
//队头出队
stack2.pop();
//stack2数据再倒给stack1
turnStack(stack2, stack1);
return top;
}
// 获取队头元素
int peek() {
turnStack(stack1, stack2);
int top = stack2.peek();
turnStack(stack2, stack1);
return top;
}
//判空
Boolean empty() {
return stack1.empty();
}
}