Skip to content

Commit bb32865

Browse files
committed
Add queue code
1 parent 50eff56 commit bb32865

File tree

2 files changed

+112
-0
lines changed

2 files changed

+112
-0
lines changed
Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
1+
package datastructure.queue;
2+
3+
import org.junit.Test;
4+
5+
import java.util.Stack;
6+
7+
import static org.hamcrest.CoreMatchers.is;
8+
import static org.junit.Assert.assertThat;
9+
10+
public class QueueWithTwoStack {
11+
@Test
12+
public void test() {
13+
MyQueue<Integer> queue = new MyQueue<>();
14+
queue.offer(1);
15+
queue.offer(2);
16+
queue.offer(3);
17+
queue.offer(4);
18+
19+
assertThat(queue.size(), is(4));
20+
21+
assertThat(queue.poll(), is(1));
22+
assertThat(queue.poll(), is(2));
23+
assertThat(queue.poll(), is(3));
24+
assertThat(queue.poll(), is(4));
25+
26+
assertThat(queue.size(), is(0));
27+
}
28+
29+
public class MyQueue<T> {
30+
private Stack<T> stack1;
31+
private Stack<T> stack2;
32+
33+
public MyQueue() {
34+
stack1 = new Stack<T>();
35+
stack2 = new Stack<T>();
36+
}
37+
38+
public void offer(T elm) {
39+
// 1. 아예 stack2를 queue와 동일하게 데이터를 저장하는 방법
40+
// while (!stack2.isEmpty()) {
41+
// stack1.push(stack2.pop());
42+
// }
43+
// stack1.push(elm);
44+
//
45+
// while (!stack1.isEmpty()) {
46+
// stack2.push(stack1.pop());
47+
// }
48+
49+
// 2. poll할 때만 queue처럼 반환하는 방법
50+
stack1.push(elm);
51+
}
52+
53+
public T poll() {
54+
// 1. 아예 stack2를 queue와 동일하게 데이터를 저장하는 방법
55+
// return stack2.pop();
56+
57+
// 2. poll할 때만 queue처럼 반환하는 방법
58+
if (stack2.isEmpty()) {
59+
while(!stack1.isEmpty()) {
60+
stack2.push(stack1.pop());
61+
}
62+
}
63+
return stack2.pop();
64+
65+
}
66+
67+
public int size() {
68+
// 1. 아예 stack2를 queue와 동일하게 데이터를 저장하는 방법
69+
// return stack2.size();
70+
71+
// 2. poll할 때만 queue처럼 반환하는 방법
72+
return stack1.size() + stack2.size();
73+
}
74+
}
75+
}
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
package datastructure.queue;
2+
3+
import org.junit.Test;
4+
5+
import java.util.LinkedList;
6+
import java.util.Queue;
7+
import java.util.Stack;
8+
9+
import static org.hamcrest.CoreMatchers.is;
10+
import static org.junit.Assert.assertThat;
11+
12+
public class ReverseQueueTest {
13+
@Test
14+
public void test() {
15+
Queue<Integer> que = new LinkedList<>();
16+
que.offer(1);
17+
que.offer(2);
18+
que.offer(3);
19+
20+
reverseQueue(que);
21+
22+
assertThat(que.poll(), is(3));
23+
assertThat(que.poll(), is(2));
24+
assertThat(que.poll(), is(1));
25+
}
26+
27+
public Queue<Integer> reverseQueue(Queue<Integer> que) {
28+
Stack<Integer> stack = new Stack<>();
29+
while (!que.isEmpty()) {
30+
stack.push(que.poll());
31+
}
32+
while(!stack.isEmpty()) {
33+
que.offer(stack.pop());
34+
}
35+
return que;
36+
}
37+
}

0 commit comments

Comments
 (0)