-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStackArray.java
More file actions
62 lines (48 loc) · 1.18 KB
/
Copy pathStackArray.java
File metadata and controls
62 lines (48 loc) · 1.18 KB
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
package Stack;
public class StackArray implements Stack{
private final int LEN=8;
private Object[] elements;
private int top;
public StackArray() {
top=-1;
elements=new Object[LEN];
}
public int getSize() {
return top+1;
}
public boolean isEmpty() {
return top<0;
}
@Override
public void push(Object e) {
// TODO Auto-generated method stub
if(getSize()>=elements.length) expandSpace();
elements[++top]=e;
}
private void expandSpace() {
Object[] a=new Object[elements.length*2];
for(int i=0;i<elements.length;i++)
a[i]=elements[i];
elements=a;
}
@Override
public Object pop() throws StackEmptyException {
// TODO Auto-generated method stub
if(getSize()<1)
throw new StackEmptyException("错误,空堆栈");
Object obj=elements[top];
elements[top--]=null;
return obj;
}
@Override
public Object peek() throws StackEmptyException {
// TODO Auto-generated method stub
if(getSize()<1)
throw new StackEmptyException("错误,堆栈为空");
return elements[top];
}
public void printStack() {
for(int i=top;i>=0;i--)
System.out.println(elements[i]);
}
}