一、两个队列实现栈
请你仅使用两个队列实现一个后入先出(LIFO)的栈,并支持普通栈的全部四种操作(push、top、pop 和 empty)。
实现 MyStack 类:
void push(int x) 将元素 x 压入栈顶。
int pop() 移除并返回栈顶元素。
int top() 返回栈顶元素。
boolean empty() 如果栈是空的,返回 true ;否则,返回 false
class MyStack { private Queue<Integer> a;//输入队列 private Queue<Integer> b;//输出队列 public MyStack() { a = new LinkedList<>(); b = new LinkedList<>(); } public void push(int x) { a.offer(x); // 将b队列中元素全部转给a队列 while(!b.isEmpty()) a.offer(b.poll()); // 交换a和b,使得a队列没有在push()的时候始终为空队列 Queue temp = a; a = b; b = temp; } public int pop() { return b.poll(); } public int top() { return b.peek(); } public boolean empty() { return b.isEmpty(); } }
二、两个栈实现队列
请你仅使用两个栈实现先入先出队列。队列应当支持一般队列支持的所有操作(push、pop、peek、empty):
实现 MyQueue 类:
void push(int x) 将元素 x 推到队列的末尾
int pop() 从队列的开头移除并返回元素
int peek() 返回队列开头的元素
boolean empty() 如果队列为空,返回 true ;否则,返回 false
class MyQueue { private Stack<Integer> a;// 输入栈 private Stack<Integer> b;// 输出栈 public MyQueue() { a = new Stack<>(); b = new Stack<>(); } public void push(int x) { a.push(x); } public int pop() { // 如果b栈为空,则将a栈全部弹出并压入b栈中,然后b.pop() if(b.isEmpty()){ while(!a.isEmpty()){ b.push(a.pop()); } } return b.pop(); } public int peek() { if(b.isEmpty()){ while(!a.isEmpty()){ b.push(a.pop()); } } return b.peek(); } public boolean empty() { return a.isEmpty() && b.isEmpty(); } }
