Skip to content

Instantly share code, notes, and snippets.

@anil477
Created May 28, 2017 17:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anil477/2a258c533428bdf387040540a57d109c to your computer and use it in GitHub Desktop.
Save anil477/2a258c533428bdf387040540a57d109c to your computer and use it in GitHub Desktop.
Implement a Queue Using Stack
import java.util.*;
class MyQueue {
private Stack<Integer> s1;
private Stack<Integer> s2;
public MyQueue()
{
this.s1 = new Stack<Integer>();
this.s2 = new Stack<Integer>();
}
public void queue(int n) {
System.out.println(" Data Queued " + n);
this.s1.push(n);
}
public void dequeue() {
if (this.s2.empty()) {
if(this.s1.empty())
{
System.out.println(" No data in Queue");
return;
}
while (!this.s1.empty()) {
this.s2.push(this.s1.pop());
}
}
System.out.println(" Data Deqeued :" + this.s2.pop());
}
public boolean empty() {
return this.s1.empty() && this.s2.empty();
}
}
class Test
{
public static void main(String[] args)
{
MyQueue obj = new MyQueue();
obj.queue(10);
obj.queue(20);
obj.queue(30);
obj.dequeue();
obj.queue(40);
obj.dequeue();
obj.dequeue();
obj.dequeue();
obj.dequeue();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment