Skip to content

Instantly share code, notes, and snippets.

@faethonm
Created March 9, 2014 22:12
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 faethonm/9455553 to your computer and use it in GitHub Desktop.
Save faethonm/9455553 to your computer and use it in GitHub Desktop.
Queue Implementation using 2 stacks. Includes implementation of get minimum
import java.util.Collections;
import java.util.Stack;
public class QueueWith2Stacks {
private Stack<Integer> stack1 =null;
private Stack<Integer> stack2 =null;
private ArrayList<Integer> minList =null;
public QueueWith2Stacks(){
this.stack1 = new Stack<Integer>();
this.stack2 = new Stack<Integer>();
this.minList= new ArrayList<Integer>();
}
public void enqueue(int data){
stack1.push(data);
minList.add(data);
Collections.sort(minList);
}
public int dequeue(){
if (stack2.isEmpty()){
while(!stack1.isEmpty()){
int temp = stack1.pop();
stack2.push(temp);
}
}
int temp = stack2.pop();
minList.remove(minList.indexOf(temp));
return temp;
}
public int getMinimum(){
return minList.get(0);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment