使用数组实现栈

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
public class MyStack {

// 存储数据
private int[] storage;
// 栈的容量
private int capacity;
// 栈中的元素
private int count;
// 栈扩大的比例
private static final int GROW_FACTOR = 2;

// 空构造法
public MyStack() {
this.storage = new int[8];
this.capacity = 8;
this.count = 0;
}

// 带容量的构造方法
public MyStack(int capacity) {
if (capacity < 1) {
throw new IllegalArgumentException("capacity illegal");
}

this.storage = new int[capacity];
this.capacity = capacity;
this.count = 0;
}

// 数据进栈
public void push(int value) {
if (count == capacity) {
ensureCapacity();
}
storage[count++] = value;
}

// 扩展栈大小
private void ensureCapacity() {
int newCapacity = capacity * GROW_FACTOR;
storage = Arrays.copyOf(storage, newCapacity);
capacity = newCapacity;
}

// 数据出栈
public int pop() {
if (count == 0) {
throw new IllegalArgumentException("Stack is empty.");
}
count--;
return storage[count];
}

// 返回栈顶元素不出栈
public int peek() {
if (count == 0) {
throw new IllegalArgumentException("Stack is empty.");
} else {
return storage[count - 1];
}
}

// 判断栈是否为空
public boolean isEmpty() {
return count == 0;
}

// 返回栈中元素的个数
public int size() {
return count;
}
}