请你仅使用两个队列实现一个后入先出(LIFO)的栈,并支持普通栈的全部四种操作(push、top、pop 和 empty)。
实现 MyStack 类:
void push(int x) 将元素 x 压入栈顶。
int pop() 移除并返回栈顶元素。
int top() 返回栈顶元素。
boolean empty() 如果栈是空的,返回 true ;否则,返回 false注意:
你只能使用队列的基本操作 —— 也就是 push to back、peek/pop from front、size 和 is empty 这些操作。
你所使用的语言也许不支持队列。 你可以使用 list (列表)或者 deque(双端队列)来模拟一个队列 , 只要是标准的队列操作即可。
public class MyStack {
// q1永远是存储元素的队列
private Queue<Integer> q1;
// q2作为辅助,每次有新元素来,都是直接添加到q2中,依次将q1中的所有元素出队再入队
private Queue<Integer> q2;
public MyStack() {
q1 = new LinkedList<>();
q2 = new LinkedList<>();
}
public void push(int x) {
q2.offer(x);
// 将q1的所有元素依次出队再入队q2
while (!q1.isEmpty()) {
q2.offer(q1.poll());
}
Queue<Integer> temp = q1;
q1 = q2;
q2 = temp;
}
public int pop() {
return q1.poll();
}
public int top() {
return q1.peek();
}
public boolean empty() {
return q1.isEmpty();
}
}
进阶:仅用一个队列来实现栈。
队列实现栈本质:旧的元素出队再入队,恰好变成了栈后进先出。
public class MyStack2 {
private Queue<Integer> queue;
public MyStack2(){
queue = new LinkedList<>();
}
public void push(int x){
// 记录当前队列的长度size
int size = queue.size();
// 新元素直接入队
queue.offer(x);
// 将之前的size个元素依次出队再入队,刚好交换顺序
for (int i = 0; i < size ; i++) {
queue.offer(queue.poll());
}
}
public int pop(){
return queue.poll();
}
public int top(){
return queue.peek();
}
public boolean empty(){
return queue.isEmpty();
}
}
请你仅使用两个栈实现先入先出队列。队列应当支持一般队列支持的所有操作(
push
、pop
、peek
、empty
):实现
MyQueue
类:
void push(int x)
将元素 x 推到队列的末尾int pop()
从队列的开头移除并返回元素int peek()
返回队列开头的元素boolean empty()
如果队列为空,返回true
;否则,返回false
说明:
- 你 只能 使用标准的栈操作 —— 也就是只有
push to top
,peek/pop from top
,size
, 和is empty
操作是合法的。- 你所使用的语言也许不支持栈。你可以使用 list 或者 deque(双端队列)来模拟一个栈,只要是标准的栈操作即可。
class MyQueue {
// s1永远是存储元素的栈
private Stack<Integer> s1;
// s2作为辅助,缓存s1之前的元素,好让新元素放在栈底(保证队尾实现)
private Stack<Integer> s2;
public MyQueue(){
s1 = new Stack<>();
s2 = new Stack<>();
}
public void push(int x) {
// 1.1保证s1中的所有元素放入s2
while (!s1.isEmpty()){
s2.push(s1.pop());
}
// 2.此时s1为空,直接将新元素添加到s1的栈底 -> 保证新元素位于队尾
s1.push(x);
// 3.再将s2中缓存的内容再依次放入s1中,压在新元素的上面,队列的先进先出
while (!s2.isEmpty()){
s1.push(s2.pop());
}
}
public int pop() {
return s1.pop();
}
public int peek() {
return s1.peek();
}
public boolean empty() {
return s1.isEmpty();
}
}