栈与队列
基中础知识
- Java中自带了对应,Stack类,Queue接口
- 也可以基于数组或者链表实现
这个写的很详细
Leecode题目
232. 用栈实现队列
- 一个栈模拟队列头部s1,另外一个模拟尾巴s2
class MyQueue {
Stack<Integer> s1;
Stack<Integer> s2;
public MyQueue() {
s1 = new Stack<>(); // 负责进栈
s2 = new Stack<>();// 负责出栈
}
public void push(int x) {
s1.push(x);
}
public int pop() {
if(s2.isEmpty()){
while(!s1.isEmpty()){
s2.push(s1.pop());
}
}
return s2.pop();
}
public int peek() {
if(s2.isEmpty()){
while(!s1.isEmpty()){
s2.push(s1.pop());
}
}
return s2.peek();
}
public boolean empty() {
return s1.isEmpty()&&s2.isEmpty();
}
}
225. 用队列实现栈
双队列实现栈
- 一个作为主要的q1,用来表示栈
- 另外一个q2用于存放临时元素
- 在q1中每次添加一个新的元素时,需要将其前面的都取出,添加完成后,再将取出的元素一次放入
class MyStack {
Queue<Integer> q1; // 和栈中保持一样元素的队列
Queue<Integer> q2; // 辅助队列
/** Initialize your data structure here. */
public MyStack() {
q1 = new ArrayDeque<>();
q2 = new ArrayDeque<>();
}
/** Push element x onto stack. */
public void push(int x) {
while(!q1.isEmpty()){
q2.add(q1.poll());
}
q1.add(x);
while(!q2.isEmpty()){
q1.add(q2.poll());
}
}
/** Removes the element on top of the stack and returns that element. */
public int pop() {
return q1.poll();
}
public int top() {
return q1.peek();
}
/** Returns whether the stack is empty. */
public boolean empty() {
return q1.isEmpty();
}
}
单队列实现
取消上面的辅助队列
- 输入一个新的元素
- 把新元素前面的a个元素依次输出再输入(==需要用size记录前面aD的大小)
满老师的讲解