标签:
Implement the following operations of a queue using stacks.
push to top
, peek/pop from top
, size
, and is empty
operations are valid.class MyQueue { Deque<Integer> stack = new ArrayDeque<Integer>(); // Push element x to the back of queue. public void push(int x) { //Organize at push stage becasue peek needs to see the top. Deque<Integer> temp = new ArrayDeque<Integer>(); while(!stack.isEmpty()){ temp.push(stack.pop()); } stack.push(x); while(!temp.isEmpty()){ stack.push(temp.pop()); } } // Removes the element from in front of queue. public void pop() { stack.pop(); } // Get the front element. public int peek() { return stack.peek(); } // Return whether the queue is empty. public boolean empty() { return stack.isEmpty(); } }
Implement the following operations of a stack using queues.
push to back
, peek/pop from front
, size
, and is empty
operations are valid.Update (2015-06-11):
The class name of the Java function had been updated to MyStack instead of Stack.
class MyStack { Deque<Integer> queue = new ArrayDeque<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(); } }
232. Implement Queue using Stacks && 225. Implement Stack using Queues
标签:
原文地址:http://www.cnblogs.com/neweracoding/p/5724491.html