forked from Gerkins/arithmeticSum
-
Notifications
You must be signed in to change notification settings - Fork 4
/
MyArrayStack.java
95 lines (78 loc) · 1.88 KB
/
MyArrayStack.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
/**
* Created by lrkin on 2016/10/26.
* 栈的数组实现
* @param <T>
*/
public class MyArrayStack<T> implements MyStack<T> {
//创建数组
private Object[] objs = new Object[16];
private int size = 0;
@Override
public boolean isEmpty() {
return size == 0;
}
@Override
public void clear() {
//将数组中的数据置为Null,方便GC进行回收
for (int i = 0; i < size; i++) {
objs[i] = null;
}
size = 0;
}
@Override
public int length() {
return size;
}
@Override
public boolean push(T data) {
//判读是否需要扩容
if (size == objs.length) {
resize();
} else {
objs[size++] = data;
}
return true;
}
private void resize() {
Object[] temp = new Object[objs.length * 3 / 2 + 1];
for (int i = 0; i < objs.length; i++) {
temp[i] = objs[i];
}
objs = temp;
}
@Override
public T pop() {
if (size > 0) {
return (T) objs[size--];
} else {
return null;
}
}
@Override
public void print() {
for (int i = 0; i < size; i++) {
System.out.print(objs[i] + "-");
}
System.out.println("");
for (int i = 0; i < objs.length; i++) {
System.out.print(objs[i] + "-");
}
}
public static void main(String[] args) {
MyStack<Integer> stack = new MyArrayStack<>();
for (int i = 0; i < 35; i++) {
stack.push(i);
}
stack.print();
System.out.println("");
for (int i = 0; i < 10 ; i++) {
stack.pop();
}
stack.print();
System.out.println("");
for (int i = 0; i < 10 ; i++) {
stack.push(i+45);
}
stack.print();
}
}