Implement Stack using 2 Queues

Costly Push Operation 

public class StackUsingTwoQueues {


Queue<Integer> queue1 = new LinkedList<>();
Queue<Integer> queue2 = new LinkedList<>();

public void push(Integer element)
{
if(element==null)
{
return;
}
while(!queue1.isEmpty())
{
queue2.add(queue1.poll());
}

queue1.add(element);

while(!queue2.isEmpty())
{
queue1.add(queue2.poll());
}
}

public int pop()
{
return queue1.poll();
}

public static void main(String args[])
{
StackUsingTwoQueues stackUsingTwoQueus = new StackUsingTwoQueues();
stackUsingTwoQueus.push(1);
stackUsingTwoQueus.push(2);
stackUsingTwoQueus.push(3);
stackUsingTwoQueus.push(4);
stackUsingTwoQueus.push(5);

System.out.println(stackUsingTwoQueus.pop());
System.out.println(stackUsingTwoQueus.pop());
System.out.println(stackUsingTwoQueus.pop());
System.out.println(stackUsingTwoQueus.pop());
System.out.println(stackUsingTwoQueus.pop());

}
}

Comments

Popular posts from this blog

Java 8 : Find the number starts with 1 from a list of integers

Junit Mockito and Power Mockito

Customized Immutable Class