forked from yangyiRunning/DataStructureAlgorithmsJava
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathArrayStack.java
More file actions
85 lines (75 loc) · 2.03 KB
/
ArrayStack.java
File metadata and controls
85 lines (75 loc) · 2.03 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
package ds;
/**
* 顺序栈(基于数组实现的栈)
*
* @author yangyi 2018年12月01日21:58:25
*/
public class ArrayStack {
private int capacity;
private Object[] objects;
private int count;
ArrayStack(int capacity) {
this.capacity = capacity;
this.objects = new Object[capacity];
this.count = 0;
}
/**
* 压栈操作
*
* @param object 压入的元素
* @return 是否成功压入
*/
private boolean push(Object object) {
if (object == null) {
return false;
}
if (count == capacity) {
return false;
}
if (count == -1) {
return false;
}
//当前的个数和数组的下标在数值上来说是相等的
objects[count] = object;
count++;
return true;
}
/**
* 弹栈操作
*
* @return 弹出的元素,没有弹出null
*/
private Object pop() {
if (count == 0) {
return null;
}
Object object = objects[count - 1];
count--;
return object;
}
/**
* 获取栈的个数
*/
private int getSize() {
return count;
}
public static void main(String[] args) {
//准备好大于100个(具体来说是101个)数用于测试
int[] ints = new int[101];
for (int i = 0; i < ints.length; i++) {
ints[i] = i;
}
ArrayStack arrayStack = new ArrayStack(100);
//将准备的好的数组顺序输出看下结果,顺便将准备好的数据依次压入栈中
for (int anInt : ints) {
System.out.println(anInt);
arrayStack.push(anInt);
}
System.out.println("————————————朴素的分割线——————————————");
int count = arrayStack.getSize();
//依次输出栈内元素看看顺序
for (int i = 0; i < count; i++) {
System.out.println(arrayStack.pop());
}
}
}