Skip to content

Instantly share code, notes, and snippets.

@deepaksinghvi
Created April 28, 2019 16:53
Show Gist options
  • Save deepaksinghvi/756388c2f85c8981291642db9c6c3904 to your computer and use it in GitHub Desktop.
Save deepaksinghvi/756388c2f85c8981291642db9c6c3904 to your computer and use it in GitHub Desktop.
Stack Using Two Queues
import java.util.LinkedList;
import java.util.Queue;
/**
* Author : Deepak Singhvi
*/
public class StackUsingQueue {
private Queue<Integer> q1 = new LinkedList<>();
private Queue<Integer> q2 = new LinkedList<>();
public static void main(String args[]){
StackUsingQueue s = new StackUsingQueue();
s.push(1);
s.push(2);
s.push(3);
System.out.println("1 :" + s.pop());
System.out.println("2 :" + s.pop());
System.out.println("3 :" + s.pop());
System.out.println("4 :" + s.pop());
}
public void push(Integer element){
q2.add(element);
while(!q1.isEmpty()) {
q2.add(q1.poll());
}
Queue<Integer> temp = q1;
q1 = q2;
q2 = temp;
}
public Integer pop() {
if(q1.isEmpty()) {
System.out.println("Queue Empty");
return null;
}
return q1.poll();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment