题目描述:
Implement the following operations of a stack using queues.
Notes:
push to back, peek/pop from front, size, and is empty operations are valid.解题思路:
代码如下:
class MyStack {
Queue<Integer> queue = new LinkedList<Integer>();
// Push element x onto stack.
public void push(int x) {
queue.offer(x);
}
// Removes the element on top of the stack.
public void pop() {
int size = queue.size();
for(int i = 1; i < size; i++)
queue.offer(queue.poll());
queue.poll();
}
// Get the top element.
public int top() {
int size = queue.size();
for(int i = 1; i < size; i++)
queue.offer(queue.poll());
int head = queue.poll();
queue.offer(head);
return head;
}
// Return whether the stack is empty.
public boolean empty() {
return queue.isEmpty();
}
}
Java [Leetcode 225]Implement Stack using Queues
原文:http://www.cnblogs.com/zihaowang/p/5164799.html