代码随想录算法训练营Day10|栈与队列part01
一、232. 用栈实现队列
栈:先入后出
队:先入先出
这里纯属用栈去模拟要使用两个栈,以此保证数字弹出顺序一致
更简单的双栈模拟队列
class MyQueue {
Stack<Integer> in;
Stack<Integer> out;
public MyQueue() {
//用一个进栈,一个出栈进行模拟
in=new Stack<>();
out=new Stack<>();
}
public void push(int x) {
//将元素 x 推到队列的末尾,即栈的最前方
in.push(x);
}
public int pop() {
//从队列的开头移除并返回元素,即弹出队头,并删除数据
allPushIn();
return out.pop();
}
public int peek() {
//peek() 返回栈顶元素,但不在堆栈中删除它。
allPushIn();
return out.peek();
}
public boolean empty() {
//由于是两个栈进行模拟,所以两个栈空即队列空
if(in.isEmpty()&&out.isEmpty()){
return true;
}
return false;
}
public void allPushIn(){
//如果out栈里面不是空的话,要想pop出,才可以继续加数据
//空的话才可以放数据
//将in的所有数据全部压入out,防止只有压入数据的时候数组顺序出错
if(!out.isEmpty()){
return;
}
while(!in.isEmpty()){
out.push(in.pop());
}
}
}
/**
* 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> qu;
// int size=0;
public MyStack() {
qu=new LinkedList<>();
}
public void push(int x) {
// 将元素 x 压入栈顶。
qu.offer(x);
// size++;
}
public int pop() {
//移除并返回栈顶元素。
//此时将队列中的所需值放到最前
//其他的元素此时弹出压入使得“栈顶”放到最前面
int temp=qu.size()-1;
while(temp-->0){
int t=qu.poll();
qu.offer(t);
}
return qu.poll();
}
public int top() {
//返回栈顶元素。即队列的最后一个
//没有back()
int temp=qu.size()-1;
while(temp-->0){
int t=qu.poll();
qu.offer(t);
}
int t=qu.poll();
qu.offer(t);
return t;
}
public boolean empty() {
if(!qu.isEmpty()){
return false;
}
return true;
}
}
/**
* 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();
*/
用两个队列来实现
class MyStack {
//q1作为主要的队列,其元素排列顺序和出栈顺序相同
Queue<Integer> q1 = new ArrayDeque<>();
//q2仅作为临时放置
Queue<Integer> q2 = new ArrayDeque<>();
public MyStack() {
}
//在加入元素时先将q1中的元素依次出栈压入q2,然后将新加入的元素压入q1,再将q2中的元素依次出栈压入q1
public void push(int x) {
while (q1.size() > 0) {
q2.add(q1.poll());
}
q1.add(x);
while (q2.size() > 0) {
q1.add(q2.poll());
}
}
public int pop() {
return q1.poll();
}
public int top() {
return q1.peek();
}
public boolean empty() {
return q1.isEmpty();
}
}