用栈实现队列
题目描述:请你仅使用两个栈实现先入先出队列。队列应当支持一般队列支持的所有操作(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(双端队列)来模拟一个栈,只要是标准的栈操作即可。
示例说明请见LeetCode官网。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/implement-queue-using-stacks/
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
解法一:双栈实现队列
MyQueue的2个栈分别为inStack和outStack,inStack用来入队列,outStack用来出队列,几个方法的主要实现逻辑如下:
push(int x):将x入栈inStack。pop():如果栈outStack不为空,直接从outStack中出栈一个;如果outStack为空,则如果inStack不为空,将inStack的全部元素出栈并且入栈outStack,然后从栈outStack中出栈一个,如果inStack也为空,则抛出异常该队列为空。peek():如果栈outStack不为空,返回outStack的栈顶元素;如果outStack为空,则如果inStack不为空,将inStack的全部元素出栈并且入栈outStack,然后返回outStack的栈顶元素,如果inStack也为空,则抛出异常该队列为空。empty():如果inStack和outStack都为空,返回true;否则返回true。
import java.util.Stack;public class LeetCode_232 {public static void main(String[] args) {MyQueue myQueue = new MyQueue();myQueue.push(1); // queue is: [1]myQueue.push(2); // queue is: [1, 2] (leftmost is front of the queue)System.out.println(myQueue.peek() == 1); // return 1System.out.println(myQueue.pop() == 1); // return 1, queue is [2]System.out.println(myQueue.empty()); // return false}}class MyQueue {private Stack<Integer> inStack;private Stack<Integer> outStack;/*** Initialize your data structure here.*/public MyQueue() {inStack = new Stack<>();outStack = new Stack<>();}/*** Push element x to the back of queue.*/public void push(int x) {inStack.push(x);}/*** Removes the element from in front of queue and returns that element.*/public int pop() {if (outStack.isEmpty()) {if (inStack.isEmpty()) {throw new RuntimeException("stack is empty.");} else {while (!inStack.isEmpty()) {outStack.push(inStack.pop());}return outStack.pop();}} else {return outStack.pop();}}/*** Get the front element.*/public int peek() {if (outStack.isEmpty()) {if (inStack.isEmpty()) {throw new RuntimeException("stack is empty.");} else {while (!inStack.isEmpty()) {outStack.push(inStack.pop());}return outStack.peek();}} else {return outStack.peek();}}/*** Returns whether the queue is empty.*/public boolean empty() {return inStack.isEmpty() && outStack.isEmpty();}
【每日寄语】 每天吃一颗糖,然后告诉自己:今天的日子,果然又是甜的。
