Implement the following operations of a queue using stacks.
push(x) -- Push element x to the back of queue.
pop() -- Removes the element from in front of queue.
peek() -- Get the front element.
empty() -- Return whether the queue is empty.
class{ Stack<Integer> stack1 = new Stack<Integer>(); Stack<Integer> stack2 = new Stack<Integer>();
publicvoidpush(int x){ stack2.add(x); }
// Removes the element from in front of queue. publicvoidpop(){ if (stack1.empty()) { while (!stack2.empty()){ // 移除 stack1.add(stack2.pop()); } stack1.pop(); } else { stack1.pop(); } }
// Get the front element. publicintpeek(){ if (stack1.empty()) { while (!stack2.empty()){ // 移除 stack1.add(stack2.pop()); } return stack1.peek(); } else { return stack1.peek(); } }
// Return whether the queue is empty. publicbooleanempty(){ return stack1.empty() && stack2.empty(); } }
近期评论