forked from JaeYeopHan/algorithm_basic_java
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathQueueWithTwoStack.java
81 lines (63 loc) · 2.06 KB
/
QueueWithTwoStack.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
package datastructure.queue;
import org.junit.Test;
import java.util.Stack;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
public class QueueWithTwoStack {
/*
TASK
Stack 두 개로 Queue를 구현한다.
*/
@Test
public void test() {
MyQueue<Integer> queue = new MyQueue<>();
queue.offer(1);
queue.offer(2);
queue.offer(3);
queue.offer(4);
assertThat(queue.size(), is(4));
assertThat(queue.poll(), is(1));
assertThat(queue.poll(), is(2));
assertThat(queue.poll(), is(3));
assertThat(queue.poll(), is(4));
assertThat(queue.size(), is(0));
}
public class MyQueue<T> {
private Stack<T> stack1;
private Stack<T> stack2;
public MyQueue() {
stack1 = new Stack<T>();
stack2 = new Stack<T>();
}
public void offer(T elm) {
// 1. 아예 stack2를 queue와 동일하게 데이터를 저장하는 방법
// while (!stack2.isEmpty()) {
// stack1.push(stack2.pop());
// }
// stack1.push(elm);
//
// while (!stack1.isEmpty()) {
// stack2.push(stack1.pop());
// }
// 2. poll할 때만 queue처럼 반환하는 방법
stack1.push(elm);
}
public T poll() {
// 1. 아예 stack2를 queue와 동일하게 데이터를 저장하는 방법
// return stack2.pop();
// 2. poll할 때만 queue처럼 반환하는 방법
if (stack2.isEmpty()) {
while(!stack1.isEmpty()) {
stack2.push(stack1.pop());
}
}
return stack2.pop();
}
public int size() {
// 1. 아예 stack2를 queue와 동일하게 데이터를 저장하는 방법
// return stack2.size();
// 2. poll할 때만 queue처럼 반환하는 방법
return stack1.size() + stack2.size();
}
}
}