Question
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
, andis 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).
Solution
1 class MyQueue { 2 Stack<Integer> stack1; 3 Stack<Integer> stack2; 4 5 public MyQueue() { 6 stack1 = new Stack<Integer>(); 7 stack2 = new Stack<Integer>(); 8 } 9 10 // Push element x to the back of queue. 11 public void push(int x) { 12 stack1.push(x); 13 } 14 15 // Removes the element from in front of queue. 16 public void pop() { 17 stack2 = new Stack<Integer>(); 18 int length = stack1.size(); 19 while (length > 1) { 20 stack2.push(stack1.pop()); 21 length--; 22 } 23 stack1.pop(); 24 length = stack2.size(); 25 while (length > 0) { 26 stack1.push(stack2.pop()); 27 length--; 28 } 29 } 30 31 // Get the front element. 32 public int peek() { 33 stack2 = new Stack<Integer>(); 34 int current = 0; 35 int length = stack1.size(); 36 while (length > 0) { 37 current = stack1.pop(); 38 stack2.push(current); 39 length--; 40 } 41 length = stack2.size(); 42 while (length > 0) { 43 stack1.push(stack2.pop()); 44 length--; 45 } 46 return current; 47 } 48 49 // Return whether the queue is empty. 50 public boolean empty() { 51 return stack1.empty(); 52 } 53 }
时间: 2024-12-09 05:18:39