Skip to content

Instantly share code, notes, and snippets.

@EsikAntony
Last active July 27, 2018 08:52
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 EsikAntony/07a73422dc98465f75c503afa7bb9827 to your computer and use it in GitHub Desktop.
Save EsikAntony/07a73422dc98465f75c503afa7bb9827 to your computer and use it in GitHub Desktop.
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import java.util.NoSuchElementException;
import java.util.Stack;
/**
* Решение задачи собеседования: сделать очередь из двух стеков
*
*/
@RunWith(JUnit4.class)
public class StackedQueueTest {
@Test
public void test() {
final MyStackedQueue<Integer> queue = new MyStackedQueue<>();
queue.push(1);
Assert.assertEquals(1, (int) queue.pop());
queue.push(2);
queue.push(3);
Assert.assertEquals(2, (int) queue.pop());
Assert.assertEquals(3, (int) queue.pop());
}
class MyStackedQueue<E> {
private Stack<E> outStack = new Stack<>();
private Stack<E> inStack = new Stack<>();
public void push(final E element) {
inStack.push(element);
}
public E pop() {
if (outStack.empty()
&& !inStack.empty()) {
while (!inStack.empty()) {
outStack.push(inStack.pop());
}
}
if (outStack.empty()) {
throw new NoSuchElementException();
} else {
return outStack.pop();
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment