Last active
August 29, 2015 14:03
-
-
Save nealhu/bdcb03625883ae62f023 to your computer and use it in GitHub Desktop.
CC_3_5
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
// Cracking the Coding Interview | |
// 3.5 Implement a MyQueue class which implements a queue using two stacks. | |
import java.util.Stack; | |
class MyQueue<T> { | |
// push stack | |
private Stack<T> s0; | |
// poll stack | |
private Stack<T> s1; | |
private int cur; | |
public MyQueue() { | |
cur = 0; | |
s0 = new Stack<T>(); | |
s1 = new Stack<T>(); | |
} | |
public void push(T element) { | |
s0.push(element); | |
} | |
public T poll() { | |
if (!s1.empty()) { | |
while(!s0.empty()) { | |
s1.push(s0.pop()); | |
} | |
} | |
return s1.pop(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment