LeetCode 232.用栈实现队列
题目链接:力扣
思路:用两个栈模拟队列的push、pop、peak等行为,其中一个是输入栈一个是输出栈,其中比较关键的是需要把输出栈都操作完所有元素之后,输入栈里面的元素才可以转入到输出栈中。
代码:
class MyQueue {
Stack<Integer> inputStack;
Stack<Integer> outputStack;
int size;
public MyQueue() {
inputStack = new Stack<>();
outputStack = new Stack<>();
size = 0;
}
public void push(int x) {
inputStack.push(x);
size++;
}
public int pop() {
if (outputStack.empty()) {
load();
}
size--;
return outputStack.pop();
}
public int peek() {
if (outputStack.empty()) {
load();
}
return outputStack.peek();
}
public boolean empty() {
if (size == 0) {
return true;
}
return false;
}
public void load() {
while (!inputStack.empty()) {
outputStack.push(inputStack.pop());
}
}
}
LeetCode 225. 用队列实现栈
题目链接:力扣
思路: 也是利用两个队列来实现栈的若干属性,其中比较关键的是如何拿到“栈顶”元素,解决方法是其中一个是输入队列,另一个作为可腾挪队列,需要得到栈顶原始时,将输入队列的N-1个元素都转移到腾挪队列中,即可在输入队列中得到栈顶元素。
代码:
class MyStack {
Queue<Integer> mainQueue;
Queue<Integer> backupQueue;
int size;
public MyStack() {
mainQueue = new ArrayDeque<>();
backupQueue = new ArrayDeque<>();
size = 0;
}
public void push(int x) {
mainQueue.offer(x);
size++;
}
public int pop() {
while (mainQueue.size() != 1) {
backupQueue.offer(mainQueue.remove());
}
int value = mainQueue.remove();
size--;
transToMQ();
return value;
}
public int top() {
if (mainQueue.size() != 1) {
transToBQ();
}
int value = mainQueue.remove();
transToMQ();
mainQueue.offer(value);
return value;
}
public boolean empty() {
return size == 0;
}
// backupQueue -> mainQueue
public void transToMQ() {
while (!backupQueue.isEmpty()) {
mainQueue.offer(backupQueue.remove());
}
}
public void transToBQ() {
while (mainQueue.size() != 1) {
backupQueue.offer(mainQueue.remove());
}
}
}