目录
1、用队列实现栈
2、用栈实现队列
1、用队列实现栈
oj:225. 用队列实现栈 - 力扣(LeetCode)
思路:
1. 入栈时,两个队列 哪个不为空放到哪个队列里,两个都是空的指定放到第一个里面
2. 出栈时,哪个不为空出哪个,出 size-1 个元素
3. 当两个队列都是空的时候,那么说明我们模拟的栈是空的
class MyStack {
private Queue<Integer> qu1;
private Queue<Integer> qu2;
public MyStack() {
qu1 = new LinkedList<>();
qu2 = new LinkedList<>();
}
public void push(int x) {
if(!qu1.isEmpty()) {
qu1.offer(x);
}else if(!qu2.isEmpty()) {
qu2.offer(x);
}else {
//两个队列都是空的 指定存放到第一个队列当中
qu1.offer(x);
}
}
public int pop() {
if(empty()) {
return -1;
}
if(!qu1.isEmpty()) {
int size = qu1.size();
for (int i = 0; i < size-1; i++) {
int x = qu1.poll();
qu2.offer(x);
}
return qu1.poll();
}else{
int size = qu2.size();
for (int i = 0; i < size-1; i++) {
int x = qu2.poll();
qu1.offer(x);
}
return qu2.poll();
}
}
public int top() {
if(empty()) {
return -1;
}
if(!qu1.isEmpty()) {
int size = qu1.size();
int x = -1;
for (int i = 0; i < size; i++) {
x = qu1.poll();
qu2.offer(x);
}
return x;
}else{
int size = qu2.size();
int x = -1;
for (int i = 0; i < size; i++) {
x = qu2.poll();
qu1.offer(x);
}
return x;
}
}
public boolean empty() {
//两个队列同时为空的时候 说明模拟实现的栈是空的!
return qu1.isEmpty() && qu2.isEmpty();
}
}
2、用栈实现队列
oj:232. 用栈实现队列 - 力扣(LeetCode)
思路:
1. 入队时,放到第一个栈里面
2. 出队时,只出第2个栈中的元素
3. 当第2个栈没有元素的时候,把第一个栈当中的元素全部倒在第二个栈中
class MyQueue {
private Stack<Integer> s1;
private Stack<Integer> s2;
public MyQueue() {
s1 = new Stack<>();
s2 = new Stack<>();
}
public void push(int x) {
s1.push(x);
}
public int pop() {
if(empty()) {
return -1;
}
if(s2.empty()) {
while (!s1.empty()) {
s2.push(s1.pop());
}
}
//
return s2.pop();
}
public int peek() {
if(empty()) {
return -1;
}
if(s2.empty()) {
while (!s1.empty()) {
s2.push(s1.pop());
}
}
return s2.peek();
}
public boolean empty() {
return s1.empty() && s2.empty();
}
}