232. 用栈实现队列
题目描述:
使用栈实现队列的下列操作:
push(x) – 将一个元素放入队列的尾部。
pop() – 从队列首部移除元素。
peek() – 返回队列首部的元素。
empty() – 返回队列是否为空。
难点:
在实现出队的时候,要注意区分情况
思路:
因为队列是FIFO的,而栈是FILO,因此要借助两个栈来实现队列
一个栈inStack
用于存放入队元素,一个outStack
用于存放出队元素。
当outStack
为空,涉及到出栈、取栈顶元素时,要将inStack
中所有元素一次性压入outStack
class MyQueue {
Stack<Integer> inStack;
Stack<Integer> outStack;
public MyQueue() {
inStack = new Stack<>();
outStack = new Stack<>();
}
public void push(int x) {
inStack.push(x);
}
public int pop() {
if (!outStack.isEmpty()) {
return outStack.pop();
}
while (!inStack.isEmpty()) {
outStack.push(inStack.pop());
}
return outStack.pop();
}
public int peek() {
if (!outStack.isEmpty()) {
return outStack.peek();
}
while (!inStack.isEmpty()) {
outStack.push(inStack.pop());
}
return outStack.peek();
}
public boolean empty() {
return inStack.isEmpty() && outStack.isEmpty();
}
}
/**
* 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();
*/
在实现中发现,涉及到peek()、pop()中有重复代码,可以抽取出来重新构建一个方法
if (!outStack.isEmpty()) {
return outStack.pop();
}
while (!inStack.isEmpty()) {
outStack.push(inStack.pop());
}
最终实现如下:
class MyQueue {
Stack<Integer> inStack;
Stack<Integer> outStack;
public MyQueue() {
inStack = new Stack<>();
outStack = new Stack<>();
}
public void push(int x) {
inStack.push(x);
}
public int pop() {
inStackDump();
return outStack.pop();
}
public int peek() {
inStackDump();
return outStack.peek();
}
public void inStackDump() {
if (outStack.isEmpty()) {
while (!inStack.isEmpty()) {
outStack.push(inStack.pop());
}
}
}
public boolean empty() {
return inStack.isEmpty() && outStack.isEmpty();
}
}
时长:
5min
收获:
栈的基本操作
225. 用队列实现栈
题目描述:
使用队列实现栈的下列操作:
- push(x) – 元素 x 入栈
- pop() – 移除栈顶元素
- top() – 获取栈顶元素
- empty() – 返回栈是否为空
思路:
仅使用一个队列即可,每次压入栈中(完成进队)后,依次将队列前n-1个元素取出,加入到队尾
class MyStack {
Queue<Integer> que;
public MyStack() {
que = new LinkedList<>();
}
public void push(int x) {
que.offer(x);
int moveNum = que.size();
while (moveNum-- > 1) {
que.offer(que.poll());
}
}
public int pop() {
return que.poll();
}
public int top() {
return que.peek();
}
public boolean empty() {
return que.isEmpty();
}
}
/**
* 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();
*/
时长:
8min
收获:
加深了队列和栈的基本操作