题目 |
题目传送门:传送门(点击此处)
题解 |
思路
- 栈的特点,先入后出;队列的特点,先入先出
- 使用队列来实现栈,每次就要把加入的元素添加到队列的头部,用来保证先入后出,所以,每次添加元素时先把队列中的元素保存到另外的一个临时队列中,然后再向当前队列中添加元素
以下的图示,表示的是添加元素时进行的操作
3. 其他的操作直接堆queue进行判断即可,比较简单
入栈时间复杂度:O(n)
出栈时间复杂度:O(1)
code
class MyStack {
Queue<Integer> queue;
Queue<Integer> queueTemp;
/**
* Initialize your data structure here.
*/
public MyStack() {
queue = new LinkedList<>();
queueTemp = new LinkedList<>();
}
/**
* Push element x onto stack.
*/
public void push(int x) {
while (!queue.isEmpty()) queueTemp.add(queue.poll());
queue.add(x);
while (!queueTemp.isEmpty()) queue.add(queueTemp.poll());
}
/**
* Removes the element on top of the stack and returns that element.
*/
public int pop() {
if (queue.isEmpty()) return -1;
else return queue.poll();
}
/**
* Get the top element.
*/
public int top() {
if (queue.isEmpty()) return -1;
else return queue.peek();
}
/**
* Returns whether the stack is empty.
*/
public boolean empty() {
return queue.isEmpty();
}
}
/**
* Your MyStack object will be instantiated and called as such:
* MyStack obj = new MyStack();
* obj.push(x);
* int param_2 = obj.pop();
* int param_3 = obj.top();
* boolean param_4 = obj.empty();
*/