- Notifications
You must be signed in to change notification settings - Fork 36
Expand file tree
/
Copy pathQueueWithTwoStack.java
More file actions
Latest commit
81 lines (63 loc) · 2.06 KB
/
Copy pathQueueWithTwoStack.java
File metadata and controls
81 lines (63 loc) · 2.06 KB
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
packagedatastructure.queue;
importorg.junit.Test;
importjava.util.Stack;
importstaticorg.hamcrest.CoreMatchers.is;
importstaticorg.junit.Assert.assertThat;
publicclassQueueWithTwoStack {
/*
TASK
Stack 두 개로 Queue를 구현한다.
*/
@Test
publicvoidtest() {
MyQueue<Integer> queue = newMyQueue<>();
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));
}
publicclassMyQueue<T> {
privateStack<T> stack1;
privateStack<T> stack2;
publicMyQueue() {
stack1 = newStack<T>();
stack2 = newStack<T>();
}
publicvoidoffer(Telm) {
// 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);
}
publicTpoll() {
// 1. 아예 stack2를 queue와 동일하게 데이터를 저장하는 방법
// return stack2.pop();
// 2. poll할 때만 queue처럼 반환하는 방법
if (stack2.isEmpty()) {
while(!stack1.isEmpty()) {
stack2.push(stack1.pop());
}
}
returnstack2.pop();
}
publicintsize() {
// 1. 아예 stack2를 queue와 동일하게 데이터를 저장하는 방법
// return stack2.size();
// 2. poll할 때만 queue처럼 반환하는 방법
returnstack1.size() + stack2.size();
}
}
}