Created
April 28, 2019 16:53
-
-
Save deepaksinghvi/756388c2f85c8981291642db9c6c3904 to your computer and use it in GitHub Desktop.
Stack Using Two Queues
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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