Created
August 8, 2015 20:12
-
-
Save bragboy/1f367a363c3e1c5683a7 to your computer and use it in GitHub Desktop.
Queue using stack
This file contains 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
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