用栈实现队列
Posted yuanjiangw
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了用栈实现队列相关的知识,希望对你有一定的参考价值。
用栈实现队列 - 力扣(LeetCode)
https://leetcode-cn.com/problems/implement-queue-using-stacks/
https://leetcode.com/problems/implement-queue-using-stacks/solution/
class MyQueue {
Stack<Integer> queue = new Stack<Integer>();
// Push element x to the back of queue.
public void push(int x) {
Stack<Integer> temp = new Stack<Integer>();
while(!queue.empty()){
temp.push(queue.pop());
}
queue.push(x);
while(!temp.empty()){
queue.push(temp.pop());
}
}
// Removes the element from in front of queue.
public int pop() {
return queue.pop();
}
// Get the front element.
public int peek() {
return queue.peek();
}
// Return whether the queue is empty.
public boolean empty() {
return queue.empty();
}
}
以上是关于用栈实现队列的主要内容,如果未能解决你的问题,请参考以下文章