Repository navigation
Expand file tree
/
Copy pathArrayStack.java
More file actions
102 lines (83 loc) · 2.13 KB
/
Copy pathArrayStack.java
File metadata and controls
102 lines (83 loc) · 2.13 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
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
package stack;
import org.testng.annotations.Test;
public class ArrayStack {
public int[] stack; // 数据存储
public int maxSize; // 栈最大数量
public int top = -1; // 栈顶位置
public ArrayStack() {
}
public ArrayStack(int maxSize) {
this.maxSize = maxSize;
stack=new int[maxSize];
}
/**
* 栈是否已满
* @return
*/
public boolean isFull(){
return top==maxSize-1;
}
/**
* 栈是否为空
* @return
*/
public boolean isEmpty(){
return top==-1;
}
/**
* 入栈:移动top指针,给数组赋值
* @param value
*/
public void push(int value) {
if(isFull()){
System.out.println("栈已满");
return;
}
//等价于top++; stack[top]=value;
stack[++top]=value;
}
/**
* 弹栈并返回弹栈的元素
* @return
*/
public int pop(){
if (isEmpty()) {
throw new RuntimeException("栈中无数据");
}
//
//等价于:1 int value=stack[top]; 先保存要弹栈的元素
// 2 top--; 栈顶指针top减一
// 3 return value; 返回弹栈的元素
return stack[top--];
}
/**
* 显示栈中数据,从栈顶开始显示,也就是按出栈的顺序显示
*/
public void print(){
if (isEmpty()) {
System.out.println("栈中无数据");
return;
}
for (int i = top; i >=0 ; i--) {
System.out.println(stack[i]);
}
}
@Test
public void pushTest() {
ArrayStack stack = new ArrayStack(4);
stack.push(2);
stack.push(1);
stack.push(4);
stack.push(3);
stack.print();
System.out.println("stack.isFull(): "+stack.isFull());
stack.push(5);//栈已满,添加失败
stack.pop();
stack.print();
stack.pop();
stack.pop();
stack.pop();
System.out.println("stack.isEmpty(): "+stack.isEmpty());
stack.pop();//java.lang.RuntimeException: 栈中无数据
}
}