Although it's a well-known algorithm, I thought to implement it from the perspective of a coding interview. I want to know if I can improve my code somehow. So, given the time constraint, is this a good enough solution to impress the interviewer?
class MyQueue {
private Stack<Integer> s1;
private Stack<Integer> s2;
MyQueue() {
s1 = new Stack<>();
s2 = new Stack<>();
}
public void enqueue(int item) {
s1.push(item);
}
private void move() {
if (s1.isEmpty()) {
throw new NoSuchElementException();
} else {
while (!s1.isEmpty()) {
s2.push(s1.pop());
}
}
}
public int peek() {
if (s2.isEmpty()) {
move();
}
return s2.peek();
}
public int dequeue() {
if (s2.isEmpty()) {
move();
}
return s2.pop();
}
}
public class Solution {
public static void main(String[] args) {
/* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */
Scanner s = new Scanner(System.in);
int N = s.nextInt();
MyQueue q = new MyQueue();
for (int i = 0; i < N; i++) {
int op = s.nextInt();
switch (op) {
case 1:
int item = s.nextInt();
q.enqueue(item);
break;
case 2:
q.dequeue();
break;
case 3:
System.out.println(q.peek());
break;
default:
System.out.println("Invalid option");
}
}
}
}