class MyStack
{
Queue<Integer> queue;
public MyStack()
{
this.queue=new LinkedList<Integer>();
}
// Push element x onto stack.
public void push(int x)
{
queue.add(x);
for(int i=0;i<queue.size()1;i++)
{
queue.add(queue.poll());
}
}
// Removes the element on top of the stack.
public void pop()
{
queue.poll();
}
// Get the top element.
public int top()
{
return queue.peek();
}
// Return whether the stack is empty.
public boolean empty()
{
return queue.isEmpty();
}
}
Only push is O(n), others are O(1). Using one queue. Combination of two shared solutions


There are two solutions cost O(n) and O(1) for different operations:
 push: O(n), pop/top: O(1)
 push: O(1), pop/top: O(n)
Time efficiency depends on operation frequency of push, pop, top:
if push>pop+top, second solution is better.
if push<pop+top, first solution is better.And I feel, in most cases, push<pop+top.
This is same idea in C++:
https://leetcode.com/discuss/46975/asimplecsolution

@YYZ90 My solution was similar, but I used a LinkedList instead :
public class StackWithQueues { private LinkedList<Integer> q; /** * Initialize your data structure here. */ public StackWithQueues() { q = new LinkedList<>(); } /** * Push element x onto stack. */ public void push(int x) { q.add(x); } /** * Removes the element on top of the stack and returns that element. */ public int pop() { return q.pollLast(); } /** * Get the top element. */ public int top() { return q.peekLast(); } /** * Returns whether the stack is empty. */ public boolean empty() { return (q.isEmpty()); } }

@sixgod Queue is an interface in Java, and the LinkedList class implement Deque which is an interface extend Queue.
You can see the java document for the detail.