forked from wangzheng0822/algo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
DynamicStackBaseArray.java
136 lines (114 loc) · 2.97 KB
/
DynamicStackBaseArray.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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
package Stack;
import java.util.Iterator;
/**
* 顺序栈的动态扩容
* Author: PeiJiaNi
* @param <T> 顺序栈元素类型
*/
public class DynamicStackBaseArray<T> implements Iterable<T> {
private T[] items; // 数组
private int count; // 栈中的元素个数
private int length; // 栈空间大小
/**
* 初始化栈
*
* @param length 栈空间大小
*/
public DynamicStackBaseArray(int length) {
this.items = (T[]) new Object[length];
this.count = 0;
this.length = length;
}
/**
* 入栈操作 平均时间复杂度O(1)
*
* @param item 入栈元素
*/
public void push(T item) {
// 栈空间已满,则扩容
if (count == length) {
resize(2 * items.length);
}
items[count++] = item;
}
/**
* 出栈操作 平均时间复杂度O(1)
*
* @return 如果栈内不为空,则返回栈顶元素,否则返回-1
*/
public T pop() {
if (count == 0) {
System.out.println("当前栈已空,无法进行出栈操作");
return null;
}
T item = items[--count];
items[count] = null;
if (count > 0 && (count == items.length / 4)) {
resize(items.length / 2);
}
// 返回下标为 count-1 的数组元素,并且栈中元素个数count-1
return item;
}
/**
* 栈空间动态增加或减小
*
* @param size
*/
private void resize(int size) {
T[] newItems = (T[]) new Object[size];
for (int i = 0; i < count; i++) {
newItems[i] = this.items[i];
}
this.items = newItems;
}
//返回栈中最近添加的元素而不删除它
public T peek() {
return items[count - 1];
}
/**
* 判断当前栈是否为空
*
* @return 栈为空,则返回true,否则返回-1
*/
public boolean isEmpty() {
return count == 0;
}
/**
* 返回栈中元素个数
*
* @return
*/
public int size() {
return count;
}
@Override
public Iterator<T> iterator() {
return new ArrayIterator();
}
// 内部类
class ArrayIterator implements Iterator {
int numOfItems = count;
@Override
public boolean hasNext() {
return numOfItems > 0;
}
@Override
public T next() {
return items[--numOfItems];
}
}
public static void main(String[] args) {
DynamicStackBaseArray<Integer> stack = new DynamicStackBaseArray<Integer>(6);
stack.push(1);
stack.push(2);
stack.push(3);
stack.push(4);
stack.push(5);
// System.out.println(stack.peek());
Iterator iterator = stack.iterator();
// System.out.println(iterator.hasNext());
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
}
}