1. 理论基础
232.用栈实现队列
-
题目解释:使用栈实现队列的下列操作:
push(x) – 将一个元素放入队列的尾部。
pop() – 从队列首部移除元素。
peek() – 返回队列首部的元素。
empty() – 返回队列是否为空。
示例:MyQueue queue = new MyQueue(); queue.push(1); queue.push(2); queue.peek(); // 返回 1 queue.pop(); // 返回 1 queue.empty(); // 返回 false
-
说明:
你只能使用标准的栈操作 – 也就是只有 push to top, peek/pop from top, size, 和 is empty 操作是合法的。
你所使用的语言也许不支持栈。你可以使用 list 或者 deque(双端队列)来模拟一个栈,只要是标准的栈操作即可。
假设所有操作都是有效的 (例如,一个空的队列不会调用 pop 或者 peek 操作)。 -
思路(去看代码随想录学习链接里的动画展示):需要两个栈,一个输入栈,一个输出栈。
push数据时,把数据放进输入栈即可;
pop时,要把输入栈的全部元素导入到输出栈里,否则就会错乱
class MyQueue {
Stack<Integer> stackIn;
Stack<Integer> stackOut;
public MyQueue() {
stackIn = new Stack<>(); //进栈
stackOut = new Stack<>(); //出栈
}
public void push(int x) {
stackIn.push(x);
}
public int pop() {
dumpstackIn();
return stackOut.pop();
}
public int peek() {
dumpstackIn();
return stackOut.peek();
}
public boolean empty() {
return stackIn.isEmpty() && stackOut.isEmpty();
}
//如果stackOut为空,就把stackIn中的元素按照出栈的顺序放到stackOut中
//这样在stackOut中,元素的顺序就反过来了,再出栈的时候就是按照队列的先进先出原则了
public void dumpstackIn() {
if(!stackOut.isEmpty()) {
return;
}
while(!stackIn.isEmpty()) {
stackOut.push(stackIn.pop());
}
}
}
225.用队列实现栈
-
题目解释:使用队列实现栈的下列操作:
push(x) – 元素 x 入栈
pop() – 移除栈顶元素
top() – 获取栈顶元素
empty() – 返回栈是否为空 -
注意:
你只能使用队列的基本操作-- 也就是 push to back, peek/pop from front, size, 和 is empty 这些操作是合法的。
你所使用的语言也许不支持队列。 你可以使用 list 或者 deque(双端队列)来模拟一个队列 , 只要是标准的队列操作即可。
你可以假设所有操作都是有效的(例如, 对一个空的栈不会调用 pop 或者 top 操作)。 -
思路:用一个队列实现栈操作,看代码随想录的讲解动画会更清楚。
class MyStack {
Queue<Integer> queue;
public MyStack() {
queue = new LinkedList<>();
}
public void push(int x) {
queue.offer(x);
}
//把前面的元素加到尾巴上;执行size-1次,原先尾巴元素就到了开头地方了。
public int pop() {
for(int i = 0; i < queue.size()-1; i++) {
queue.offer(queue.poll());
}
return queue.poll();
}
//和pop一样,先把开头的存到res了,再把res的加到尾巴上,在返回res。
public int top() {
for(int i = 0; i < queue.size()-1; i++) {
queue.offer(queue.poll());
}
int res = queue.poll();
queue.offer(res);
return res;
}
public boolean empty() {
return queue.isEmpty();
}
}