Skip to content

Instantly share code, notes, and snippets.

@skmangalam
Created March 14, 2018 05:59
Show Gist options
  • Select an option

  • Save skmangalam/08eff91f7004007fd347b69a19b6b452 to your computer and use it in GitHub Desktop.

Select an option

Save skmangalam/08eff91f7004007fd347b69a19b6b452 to your computer and use it in GitHub Desktop.
Implementation of Queue using Stacks
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");
}
}
}
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