Implement the following operations of a stack using queues.
- push(x) -- Push element x onto stack.
- pop() -- Removes the element on top of the stack.
- top() -- Get the top element.
- empty() -- Return whether the stack is empty.
思路:采用两个队列模拟
时间复杂度:
代码:
class MyStack { Queue<Integer> queue1=new LinkedList<Integer>(); Queue<Integer> queue2=new LinkedList<Integer>(); int size=0; // Push element x onto stack. public void push(int x) { queue1.offer(x); size++; } // Removes the element on top of the stack. public void pop() { while(size!=1) { queue2.offer(queue1.poll()); size--; } if(size==1) { queue1.poll(); size--; } while(!queue2.isEmpty()) { push(queue2.poll()); } } // Get the top element. public int top() { int ret=0; while(size!=1) { queue2.offer(queue1.poll()); size--; } if(size==1) { ret=queue1.peek(); queue2.offer(queue1.poll()); size--; } while(!queue2.isEmpty()) { push(queue2.poll()); } return ret; } // Return whether the stack is empty. public boolean empty() { return queue1.isEmpty(); } }
注意 peek后还得再次入队
优化:这里采用的是两个队列,由于队列FIFO,两个队列的使用就相当于在一个队列中开了个口子,从口子中放水,然后再流回去,能否采用一个队列呢?每次出队列就再次压入。
class MyStack { Queue<Integer> que=new LinkedList<Integer>(); int size=0; // Push element x onto stack. public void push(int x) { que.offer(x); size++; } // Removes the element on top of the stack. public void pop() { int index=size; while(index!=1) { que.offer(que.poll()); index--; } if(index==1) { que.poll(); index--; size--; } } // Get the top element. public int top() { int ret=0; int index=size; while(index!=1) { que.offer(que.poll()); index--; } if(index==1) { ret=que.peek(); que.offer(que.poll()); } return ret; } // Return whether the stack is empty. public boolean empty() { return que.isEmpty(); } }
扩展: