Skip to content

Commit d895636

Browse files
committed
顺序栈实现
1 parent bbe7900 commit d895636

File tree

1 file changed

+64
-0
lines changed

1 file changed

+64
-0
lines changed

StackBaseArray.java

+64
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
package Stack;
2+
3+
/**
4+
* 顺序栈(基于数组实现)
5+
* Author: PeiJiaNi
6+
*/
7+
public class StackBaseArray {
8+
private int[] items; // 数组
9+
private int count; // 栈中元素个数
10+
private int length; // 栈空间大小
11+
12+
public StackBaseArray(int capactiy) {
13+
this.items = new int[capactiy];
14+
this.count = 0;
15+
this.length = capactiy;
16+
}
17+
18+
/**
19+
* 入栈操作 时间复杂度O(1)
20+
* @param item 要入栈的元素
21+
* @return 入栈成功则返回true,否则返回false
22+
*/
23+
public boolean push(int item) {
24+
if(count == length) {
25+
System.out.println("当前栈已满,无法进行入栈操作");
26+
return false;
27+
}
28+
items[count] = item;
29+
++count;
30+
return true;
31+
}
32+
33+
/**
34+
* 出栈操作 时间复杂度O(1)
35+
* @return 如果栈内不为空,则返回栈顶元素,否则返回-1
36+
*/
37+
public int pop(){
38+
if(count == 0) {
39+
System.out.println("当前栈已空,无法进行出栈操作");
40+
return -1;
41+
}
42+
43+
// 返回下标为 count-1 的数组元素,并且栈中元素个数count-1
44+
return items[--count];
45+
}
46+
47+
public static void main(String[] args){
48+
StackBaseArray stack = new StackBaseArray(6);
49+
stack.push(1);
50+
stack.push(2);
51+
stack.push(3);
52+
stack.push(4);
53+
stack.push(5);
54+
System.out.println(stack.pop());
55+
System.out.println(stack.pop());
56+
System.out.println(stack.pop());
57+
System.out.println(stack.pop());
58+
System.out.println(stack.pop());
59+
60+
}
61+
62+
63+
}
64+

0 commit comments

Comments
 (0)