|
| 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 | +} |
0 commit comments