Created
March 14, 2018 05:59
-
-
Save skmangalam/08eff91f7004007fd347b69a19b6b452 to your computer and use it in GitHub Desktop.
Implementation of Queue using Stacks
This file contains hidden or 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.Stack; | |
| public class Queue { | |
| private Stack s1; | |
| private Stack s2; | |
| public Queue() { | |
| this.s1 = new Stack<Integer>(); | |
| this.s2 = new Stack<Integer>(); | |
| } | |
| public void enqueue(int data){ | |
| s1.push(data); | |
| } | |
| public void dequeue(){ | |
| if(!s2.isEmpty()){ | |
| //pop from stack s2 | |
| System.out.println(s2.pop()+" is dequeued"); | |
| } | |
| else{ | |
| //pop each item from stack s1 and push into stack s2 | |
| while(!s1.isEmpty()){ | |
| s2.push(s1.pop()); | |
| } | |
| //Now stack s1 is empty | |
| //finally, pop from stack s2 | |
| System.out.println(s2.pop()+" is dequeued"); | |
| } | |
| } | |
| } |
This file contains hidden or 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
| public class Test { | |
| public static void main(String[] args) { | |
| Queue q = new Queue(); | |
| q.enqueue(10); | |
| q.enqueue(20); | |
| q.dequeue(); | |
| q.enqueue(30); | |
| q.dequeue(); | |
| q.enqueue(40); | |
| q.enqueue(50); | |
| q.dequeue(); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment