Skip to content

Instantly share code, notes, and snippets.

@bragboy
Created August 8, 2015 20:12
Show Gist options
  • Save bragboy/1f367a363c3e1c5683a7 to your computer and use it in GitHub Desktop.
Save bragboy/1f367a363c3e1c5683a7 to your computer and use it in GitHub Desktop.
Queue using stack
package dsa.stack;
import java.util.Stack;
/**
* An implementation of Queue using two Stacks
* @author Braga
*/
public class QueueStack<T>{
private Stack<T> firstStack;
private Stack<T> secondStack;
public QueueStack(){
firstStack = new Stack<T>();
secondStack = new Stack<T>();
}
public QueueStack<T> enQueue(T item) {
firstStack.push(item);
return this;
}
public T deQueue() {
if(!secondStack.isEmpty()){
return secondStack.pop();
}else if(!firstStack.isEmpty()){
while(!firstStack.isEmpty()){
secondStack.push(firstStack.pop());
}
return secondStack.pop();
}
return null;
}
public int size() {
return firstStack.size() + secondStack.size();
}
public boolean isEmpty(){
if (size() == 0) {
return true;
}
return false;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment