|
| 1 | +package datastructure.stack; |
| 2 | + |
| 3 | +import org.junit.Test; |
| 4 | + |
| 5 | +import static org.hamcrest.CoreMatchers.is; |
| 6 | +import static org.junit.Assert.assertThat; |
| 7 | + |
| 8 | +public class MyStackWithArrayTest { |
| 9 | + @Test |
| 10 | + public void test() { |
| 11 | + MyStackWithArray stack = new MyStackWithArray(); |
| 12 | + |
| 13 | + stack.push(0); |
| 14 | + stack.push(1); |
| 15 | + stack.push(2); |
| 16 | + stack.push(3); |
| 17 | + stack.push(4); |
| 18 | + stack.push(5); |
| 19 | + stack.push(6); |
| 20 | + |
| 21 | + assertThat(6, is(stack.pop())); |
| 22 | + assertThat(5, is(stack.pop())); |
| 23 | + assertThat(4, is(stack.pop())); |
| 24 | + assertThat(3, is(stack.pop())); |
| 25 | + assertThat(2, is(stack.pop())); |
| 26 | + assertThat(1, is(stack.pop())); |
| 27 | + assertThat(0, is(stack.pop())); |
| 28 | + |
| 29 | +// java.lang.RuntimeException: Empty Stack! |
| 30 | +// assertThat(0, is(stack.pop())); |
| 31 | + } |
| 32 | + |
| 33 | + public class MyStackWithArray { |
| 34 | + private int[] data = new int[5]; |
| 35 | + private int topIndex = -1; |
| 36 | + |
| 37 | + public synchronized void push(int i) { |
| 38 | + topIndex++; |
| 39 | + if (topIndex >= data.length) { |
| 40 | + int[] oldData = data; |
| 41 | + data = new int[data.length * 2]; |
| 42 | +// System.arraycopy(oldData, 0, data, 0, oldData.length); |
| 43 | + for (int j = 0; j < oldData.length; j++) { |
| 44 | + data[j] = oldData[j]; |
| 45 | + } |
| 46 | + } |
| 47 | + |
| 48 | + data[topIndex] = i; |
| 49 | + } |
| 50 | + |
| 51 | + public synchronized int pop() { |
| 52 | + if (topIndex < 0) { |
| 53 | + throw new RuntimeException("Empty Stack!"); |
| 54 | + } |
| 55 | +// int result = data[topIndex]; |
| 56 | +// topIndex--; |
| 57 | + return data[topIndex--]; |
| 58 | + } |
| 59 | + } |
| 60 | +} |
0 commit comments