//implement a queue using stack
public class Solution {
Stack<Integer> stack1 = new Stack<Integer>();
Stack<Integer> stack2 = new Stack<Integer>();
//pop: dequeue in stack1
public void dequeue() {
if (stack1.peek() == null) {
System.out.println("The queue is empty!");
} else {
int pop = stack1.pop();
return pop;
}
}
//1.pop all the items from stack1 to stack2
//2.push the new item in stack1
//3.pop all the items in stack2 to stack1
public void enqueue(int data) {
if (stack.peek() == null) {
stack1.push(data);
} else {
for (int i = stack1.size(); i > 0; i--) {
stack2.push(stack1.pop());
}
stack1.push(data);
for (int j = stack2.size(); j > 0; j--) {
stack1.push(stack2.pop());
}
}
}
}
The solution is similar to implement a stack using queue.