0%

基于数组的stack结构实现

基于数组的stack结构实现

接口定义

1
2
3
4
5
6
7
8
9
10
11
12
public interface Stack {
//栈大小
int getSize();
//入栈
void push(Object o);
//出栈
Object pop();
//是否为空
boolean isEmpty();
//查看栈顶端元素,不删除
Object top();
}

异常定义

1
2
3
4
5
6
7
8
9
10
11
public class StackEmptyException extends RuntimeException{
public StackEmptyException(String message) {
super(message);
}
}

public class StackOverFlowException extends RuntimeException {
public StackOverFlowException(String message) {
super(message);
}
}

实现

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
public class ArrayStack implements Stack{
//默认数组长度
private static final int DEFAULT_CAPACITY=1024;
//栈顶位置
private int top_position=-1;
//栈数组
private Object[] stack;
//实际数组长度
private int capacity;

public ArrayStack() {
this(DEFAULT_CAPACITY);
}

public ArrayStack(int capacity) {
this.capacity = capacity;
stack=new Object[capacity];
}

@Override
public int getSize() {
return top_position+1;
}

@Override
public void push(Object o) {
if(getSize()<capacity){
stack[++top_position]=o;
}else {
throw new StackOverFlowException("栈溢出");
}
}

@Override
public Object pop() {
if(!isEmpty()){
Object element=stack[top_position];
stack[top_position--]=null;
return element;
}else {
throw new StackEmptyException("空栈");
}
}

@Override
public boolean isEmpty() {
return top_position<0;
}

@Override
public Object top() {
if(!isEmpty()){
return stack[top_position];
}else {
throw new StackEmptyException("空栈");
}
}
}