标签:
题目:
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来模拟stack,用queue的基本操作
思路:比较简单,用两个queue来进行即可,一个作为模拟的stack存储,一个运来转换中间的操作数字
代码:
class MyStack { LinkedList<Integer> queue = new LinkedList<Integer>(); LinkedList<Integer> temp = new LinkedList<Integer>(); // Push element x onto stack. public void push(int x) { while(!queue.isEmpty()){ temp.offer(queue.poll()); } queue.offer(x); while(!temp.isEmpty()){ queue.offer(temp.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(); } }
[LeetCode-JAVA] Implement Stack using Queues
标签:
原文地址:http://www.cnblogs.com/TinyBobo/p/4590385.html