用栈实现队列

 

用栈实现队列 - 力扣(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();
}
}

 

posted @ 2019-05-03 23:24  papering  阅读(160)  评论(0编辑  收藏  举报