两个队列实现栈
力扣简单习题:
大致思路
代码实现
package com.immunize.leetcode.implementQueue;
import java.util.LinkedList;
/**
* 使用队列实现栈
*
* @author Mr IMMUNIZE
*
*/
class Queue2Stack {
// 两个队列
private LinkedList<Integer> queue1;
private LinkedList<Integer> queue2;
// 构造器初始化两个队列
public Queue2Stack() {
queue1 = new LinkedList<Integer>();
queue2 = new LinkedList<Integer>();
}
// 入栈操作:找到非空栈,将元素放入非空栈
public void push(int x) {
if (queue1.isEmpty() && queue2.isEmpty()) {
queue1.addLast(x);
} else if (queue1.isEmpty()) {
queue2.addLast(x);
} else {
queue1.addLast(x);
}
}
// 出栈:将非空栈q1(q2)中的1-倒数第二个元素出栈,并且放入q2(q1),剩余的最后一个出队,即为出栈操作
public int pop() {
if (queue1.isEmpty()) {
int len = queue2.size();
for (int i = 0; i < len - 1; i++) {
queue1.addLast(queue2.removeFirst());
}
return queue2.removeFirst();
} else {
int len = queue1.size();
for (int i = 0; i < len - 1; i++) {
queue2.addLast(queue1.removeFirst());
}
return queue1.removeFirst();
}
}
// 非空队列中的最后一个元素即为栈顶元素,也就是最后一个进来的
public int top() {
if (queue1.isEmpty()) {
return queue2.getLast();
} else {
return queue1.getLast();
}
}
// 两个队列都空的时候,视为栈空
public boolean empty() {
return queue1.isEmpty() && queue2.isEmpty();
}
}
-------------------------------------------------------------------------------------------
package com.immunize.leetcode.implementQueue;
/**
* 测试
*
* @author Mr IMMUNIZE
*
*/
public class Queue2Stack_Test {
public static void main(String[] args) {
Queue2Stack q2s = new Queue2Stack();
q2s.push(5);
q2s.push(4);
q2s.push(3);
q2s.push(2);
q2s.push(1);
System.out.println(q2s.top());
q2s.pop();
System.out.println(q2s.top());
}
}