https://leetcode.com/problems/implement-queue-using-stacks/description/
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.
Notes:
You must use only standard operations of a stack -- which means only push to top, peek/pop from top, size, and is empty operations are valid.
Depending on your language, stack may not be supported natively. You may simulate a stack by using a list or deque (double-ended queue), as long as you use only standard operations of a stack.
You may assume that all operations are valid (for example, no pop or peek operations will be called on an empty queue).
worse case出现在 所有元素都在stack1 中,第一次 从 stack2 中 pop
1 public class LC_232_ImplementQueueUsingStacks {
2 private Deque<Integer> stack1;
3 private Deque<Integer> stack2;
4
5 /**
6 * Initialize your data structure here.
7 */
8 public LC_232_ImplementQueueUsingStacks() {
9 stack1 = new LinkedList<>();
10 stack2 = new LinkedList<>();
11 }
12
13 /**
14 * Push element x to the back of queue.
15 */
16 public void push(int x) {
17 stack1.push(x);
18 }
19
20 /**
21 * Removes the element from in front of queue and returns that element.
22 */
23 public int pop() {
24 if (!stack2.isEmpty()) {
25 return stack2.pop();
26 } else {
27 shuffle();
28 return stack2.pop();
29 }
30 }
31
32 /**
33 * Get the front element.
34 */
35 public int peek() {
36 if (!stack2.isEmpty()) {
37 return stack2.peek();
38 } else {
39 shuffle();
40 return stack2.peek();
41 }
42 }
43
44 private void shuffle() {
45 while (!stack1.isEmpty()) {
46 stack2.push(stack1.pop());
47 }
48 }
49
50 /**
51 * Returns whether the queue is empty.
52 */
53 public boolean empty() {
54 return stack1.isEmpty() && stack2.isEmpty();
55 }
56 }