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.
//方法1 push() O(n), pop() O(1), peek() O(1) class MyQueue { Stack<Integer> stack = new Stack<Integer>(); Stack<Integer> tem = new Stack<Integer>(); public void push(int x) { if (stack.isEmpty()) { stack.push(x); } else { while (!stack.isEmpty()) { tem.push(stack.pop()); } tem.push(x); while (!tem.isEmpty()) { stack.push(tem.pop()); } } } public void pop() { stack.pop(); } public int peek() { return stack.peek(); } public boolean empty() { return stack.isEmpty(); } } //方法2 push() O(1), pop() O(n), peek() O(n) class MyQueue { private Stack<Integer> stack = new Stack<Integer>(); private Stack<Integer> tem = new Stack<Integer>(); public void push(int x) { stack.push(x); } public void pop() { int x = peek(); tem.pop(); } public int peek() { if (tem.isEmpty()) { while (!stack.isEmpty()) { tem.push(stack.pop()); } } return tem.peek(); } public boolean empty() { return stack.isEmpty() && tem.isEmpty(); } }
没有评论:
发表评论