用栈实现队列(Java)
基本知识
1. 栈stack
- 栈先进后出,继承vector
- 创建栈:Stack sk = new Stack<>();
- sk.push(x) – 将一个元素放入队列的尾部。
- sk.pop() – 从队列首部移除并返回该元素。
- sk.peek() – 返回队列首部的元素。
- sk.empty() – 返回队列是否为空。
2. 队列queue
- 队列先进先出
- 创建队列:Queue q = new LinkedList<>();
- q.offer() --入队列
- q.poll() --出队列
- q.peek() --获取队头元素
- q.isEmpty() --检测队列是否为空
题目
基本思路:使用两个栈(输入栈和输出栈共同完成一个队列),保证把进栈数据全部导入到输出栈(注意是全部导入)。
注意:将相近功能的代码抽象出来
class MyQueue {
Stack<Integer> sin;
Stack<Integer> sout;
public MyQueue() {
sin = new Stack<>(); // 创建栈
sout = new Stack<>();
}
public void push(int x) {
sin.push(x);
}
public int pop() {
absfuc();
return sout.pop();
}
public int peek() {
absfuc();
return sout.peek();
}
public boolean empty() {
if(sout.empty()&& sin.empty()){ //为空的写法
return true;
}
else{
return false;
}
}
// 把方法抽象出来
public void absfuc(){
while(!sout.empty()){//注意一下不为null的写法
return; //退出方法
}
while(!sin.empty()){
sout.push(sin.pop());
}
}
}
队列实现栈(Java)
方法1: 双队列
思路:最新来的一定要在出栈口(一个个叠加),用que2作为存放新来的队列。而为了实现倒序叠加,需要做一个如下图的交换:
解释:每次push新元素时,都将其放入一个空队列,然后将另一个队列的所有元素转移到这个队列中,最后交换两个队列的引用
class MyStack {
Queue<Integer> que1;
Queue<Integer> que2;
public MyStack() {
que1 = new LinkedList<>(); //创建队列
que2 = new LinkedList<>();
}
public void push(int x) {
//新添加的在2的出站口
que2.offer(x);
while(!que1.isEmpty()){
que2.offer(que1.poll());
}
Queue<Integer> temp = new LinkedList<>(); //必须要新建一个
temp = que1;
que1 = que2;
que2 = temp;
}
public int pop() {
return que1.poll();
}
public int top() {
return que1.peek();
}
public boolean empty() {
if(que1.isEmpty()){
return true;
}
else{
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();
*/
方法2:单队列
思想:要将队列头部的元素(除了最后一个元素外) 重新添加到队列尾部,如图:
注意:在push方法里就要随时进行这种变化。
class MyStack {
Queue<Integer> que;
public MyStack() {
que = new LinkedList<>(); //创建队列
}
public void push(int x) {
que.offer(x);
int count = que.size();
while(count > 1){
que.offer(que.poll());
count--;
}
}
public int pop() {
return que.poll();
}
public int top() {
return que.peek();
}
public boolean empty() {
if(que.isEmpty()){
return true;
}
else{
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();
*/
写博客的目的是每日督促并记录刷题,也欢迎大家批评指正~(day12)