2020-ARTS-打卡第九天
Algorithm 题目一 题目描述 使用栈实现队列的操作:push(), peek(), pop(), empty()操作,只能使用标准的栈操作 – 也就是只有 push to top, peek/pop from top, size, 和 is empty 操作是合法的。232 用栈实现队列 题目解答 由于队列是FIFO,而栈是FILO,要想使用栈来实现队列,则可以使用两个栈来达到目的,即负负到正,核心点就是pop()和peek()方法的处理上,在调用pop()与peek()方法时都在要从outStack中来操作,如果outStack不为空,则直接进行操作,否则要把inStack中的元素添加到outStack中。 import java.util.Iterator; import java.util.Stack; class MyQueue { private Stack<Integer> inputStack; private Stack<Integer> outStack; /** Initialize your data structure here. */ public MyQueue() { inputStack = new Stack<>(); outStack = new Stack<>(); } /** Push element x to the back of queue. */ public void push(int x) { inputStack.push(x); } /** Removes the element from in front of queue and returns that element. */ public int pop() { if (empty()) { return -1; } if (outStack.empty()) { while (!inputStack.empty()) { outStack.push(inputStack.pop()); } } return outStack.pop(); } /** Get the front element. */ public int peek() { if (empty()) { return -1; } if (outStack.empty()) { while (!inputStack.empty()) { outStack.push(inputStack.pop()); } } return outStack.peek(); } /** Returns whether the queue is empty. */ public boolean empty() { return inputStack.empty() && outStack.empty(); } } 时间复杂度:push O(1), pop O(n), peek O(n) ...