Idea: Implement Queue by using two Stacks: in & out
Stack in: Insert all value into this StackStack out: reverse order of in stack
class MyQueue{
Stack<Integer> in;
Stack<Integer> out;
MyQueue(){
in=new Stack();
out=new Stack();
}
public void EnQueue(int data){
in.push(data);
System.out.println("Add " + data + " in queue!");
}
private void shiftReverse(){
if(out.isEmpty()){
//push reverse order into out Stack
while(!in.isEmpty()){
out.push(in.pop());
}
}
}
public int DeQueue(){
shiftReverse();
if(out.isEmpty()){
System.out.println("Queue is empty, cannot remove!");
return -1;
}
System.out.println("Remove " + out.peek() + " from queue!");
return out.pop();
}
public int FirstElement(){
shiftReverse();
if( out.isEmpty() ) {
System.out.println("Queue is empty, cannot peek!");
return -1;
}
System.out.println("First element in queue: " + out.peek());
return out.peek();
}
}