Created
May 28, 2017 17:19
-
-
Save anil477/2a258c533428bdf387040540a57d109c to your computer and use it in GitHub Desktop.
Implement a Queue Using Stack
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.*; | |
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