标签:
https://leetcode.com/problems/implement-stack-using-queues/
Implement the following operations of a stack using queues.
Notes:
push to back
, peek/pop from front
, size
, and is empty
operations are valid.解题思路:
用了俩queue,思路就很明确了。需要peek或者pop的时候,将一个queue中的元素插入另一个queue,直到只剩一个了,这样才能获得尾端的元素。
也可以只用一个queue,但是在push的时候,就将所有元素立刻反向。
崩溃的是,Queue这个interface,居然没有empty()的方法,连size()的方法都没有。
class MyStack { LinkedList<Integer> queue1 = new LinkedList<Integer>(); LinkedList<Integer> queue2 = new LinkedList<Integer>(); // Push element x onto stack. public void push(int x) { if(queue1.size() > 0) { queue1.offer(x); } else { queue2.offer(x); } } // Removes the element on top of the stack. public void pop() { if(queue1.size() == 0) { LinkedList<Integer> temp = queue1; queue1 = queue2; queue2 = temp; } while(queue1.size() > 1) { queue2.offer(queue1.poll()); } queue1.poll(); } // Get the top element. public int top() { if(queue1.size() == 0){ LinkedList<Integer> temp = queue1; queue1 = queue2; queue2 = temp; } while(queue1.size() > 1) { queue2.offer(queue1.poll()); } int res = queue1.peek(); queue2.offer(queue1.poll()); return res; } // Return whether the stack is empty. public boolean empty() { return queue1.size() == 0 && queue2.size() == 0; } }
标签:
原文地址:http://www.cnblogs.com/NickyYe/p/4573541.html