-
Notifications
You must be signed in to change notification settings - Fork 37
/
Copy pathMyStackWithArrayTest.java
66 lines (54 loc) · 1.69 KB
/
MyStackWithArrayTest.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
package datastructure.stack;
import org.junit.Test;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
public class MyStackWithArrayTest {
/*
TASK
Array를 사용하여 Stack을 구현한다.
*/
@Test
public void test() {
MyStackWithArray stack = new MyStackWithArray();
stack.push(0);
stack.push(1);
stack.push(2);
stack.push(3);
stack.push(4);
stack.push(5);
stack.push(6);
assertThat(stack.pop(), is(6));
assertThat(stack.pop(), is(5));
assertThat(stack.pop(), is(4));
assertThat(stack.pop(), is(3));
assertThat(stack.pop(), is(2));
assertThat(stack.pop(), is(1));
assertThat(stack.pop(), is(0));
// java.lang.RuntimeException: Empty Stack!
// assertThat(0, is(stack.pop()));
}
public class MyStackWithArray {
private int[] data = new int[5];
private int topIndex = -1;
public synchronized void push(int i) {
topIndex++;
if (topIndex >= data.length) {
int[] oldData = data;
data = new int[data.length * 2];
// System.arraycopy(oldData, 0, data, 0, oldData.length);
for (int j = 0; j < oldData.length; j++) {
data[j] = oldData[j];
}
}
data[topIndex] = i;
}
public synchronized int pop() {
if (topIndex < 0) {
throw new RuntimeException("Empty Stack!");
}
// int result = data[topIndex];
// topIndex--;
return data[topIndex--];
}
}
}