Created
March 9, 2014 22:12
-
-
Save faethonm/9455553 to your computer and use it in GitHub Desktop.
Queue Implementation using 2 stacks. Includes implementation of get minimum
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.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