|
Implement enqueue and dequeue operations using stack(s).
Microsoft Interview Questions and Answers
(Continued from previous question...)
132. Implement enqueue and dequeue operations using stack(s).
Question:
Implement enqueue and dequeue operations using stack(s).
maybe an answer:
No need to push elements on to the second stack whenever a enqueue is requested. Just keep adding to first stack. When a dequeue is requested check if there are elements on stack2, if stack2 is empty keep popping from the first stack and placing them onto second stack until the requested number of pops.
Only thing need to remember is always dequeue happens from stack2 and enqueue happens in stack1.
1 public class MyQueue<T> {
2 Stack<T> s1, s2;
3 public MyQueue() {
4 s1 = new Stack<T>();
5 s2 = new Stack<T>();
6 }
7
8 public int size() {
9 return s1.size() + s2.size();
10 }
11
12 public void add(T value) {
13 s1.push(value);
14 }
15
16 public T peek() {
17 if (!s2.empty()) return s2.peek();
18 while (!s1.empty()) s2.push(s1.pop());
19 return s2.peek();
20 }
21
22 public T remove() {
23 if (!s2.empty()) return s2.pop();
24 while (!s1.empty()) s2.push(s1.pop());
25 return s2.pop();
26 }
27 }
(Continued on next question...)
Other Interview Questions
|