Skip to content

Commit 0a6065f

Browse files
committed
2개 스택으로 큐를 구현해보기
1 parent 24a965c commit 0a6065f

File tree

2 files changed

+78
-0
lines changed

2 files changed

+78
-0
lines changed
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
package io.github.gunkim.algorithm.queue;
2+
3+
import java.util.Stack;
4+
5+
public class TwoStackQueue<T> {
6+
private final Stack<T> inStack = new Stack<>();
7+
private final Stack<T> outStack = new Stack<>();
8+
9+
public void add(T value) {
10+
inStack.push(value);
11+
}
12+
13+
public T get() {
14+
if (outStack.isEmpty()) {
15+
while (!inStack.isEmpty()) {
16+
T value = inStack.pop();
17+
outStack.push(value);
18+
}
19+
}
20+
return outStack.pop();
21+
}
22+
}
Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
package io.github.gunkim.algorithm.queue;
2+
3+
import org.junit.jupiter.api.Test;
4+
5+
import static org.assertj.core.api.Assertions.assertThat;
6+
import static org.assertj.core.api.Assertions.assertThatThrownBy;
7+
8+
class TwoStackQueueTest {
9+
@Test
10+
void 요소가_순서대로_검색되는지_테스트() {
11+
TwoStackQueue<Integer> queue = new TwoStackQueue<>();
12+
queue.add(1);
13+
queue.add(2);
14+
queue.add(3);
15+
16+
assertThat(queue.get()).isEqualTo(1);
17+
assertThat(queue.get()).isEqualTo(2);
18+
assertThat(queue.get()).isEqualTo(3);
19+
}
20+
21+
@Test
22+
void 추가와_조회_작업이_번갈아_수행되는지_테스트() {
23+
TwoStackQueue<Integer> queue = new TwoStackQueue<>();
24+
queue.add(1);
25+
queue.add(2);
26+
27+
assertThat(queue.get()).isEqualTo(1);
28+
29+
queue.add(3);
30+
assertThat(queue.get()).isEqualTo(2);
31+
assertThat(queue.get()).isEqualTo(3);
32+
}
33+
34+
@Test
35+
void 빈_큐에서_예외가_발생하는지_테스트() {
36+
TwoStackQueue<Integer> queue = new TwoStackQueue<>();
37+
38+
assertThatThrownBy(queue::get)
39+
.isInstanceOf(java.util.EmptyStackException.class);
40+
}
41+
42+
@Test
43+
void 큐를_비우고_다시_채운후_조회하는_테스트() {
44+
TwoStackQueue<Integer> queue = new TwoStackQueue<>();
45+
queue.add(1);
46+
queue.add(2);
47+
queue.get();
48+
queue.get();
49+
50+
queue.add(3);
51+
queue.add(4);
52+
53+
assertThat(queue.get()).isEqualTo(3);
54+
assertThat(queue.get()).isEqualTo(4);
55+
}
56+
}

0 commit comments

Comments
 (0)