Skip to content

Commit 02dae84

Browse files
committed
顺序栈
1 parent dfe0cb5 commit 02dae84

File tree

3 files changed

+104
-0
lines changed

3 files changed

+104
-0
lines changed

README.md

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,12 @@
4242
[circular-linked-list]: ./src/com/fantasy/datastructure/linkedlist/CircularLinkedList.java
4343
[doubly-linked-list]: ./src/com/fantasy/datastructure/linkedlist/DoublyLinkedList.java
4444

45+
###
46+
47+
- [顺序栈][array-stack]
48+
49+
[array-stack]: ./src/com/fantasy/datastructure/stack/ArrayStack.java
50+
4551
### 二叉树
4652

4753
- [实现一个二叉查找树,支持增删查改操作][binary-search-tree]
Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
package com.fantasy.datastructure.stack;
2+
3+
/**
4+
* 顺序栈
5+
*
6+
* <pre>
7+
* author : Fantasy
8+
* version : 1.0, 2020-08-30
9+
* since : 1.0, 2020-08-30
10+
* </pre>
11+
*/
12+
public class ArrayStack {
13+
/**
14+
* 数组容器
15+
*/
16+
private int[] mData;
17+
/**
18+
* 当前元素个数
19+
*/
20+
private int mSize;
21+
22+
public ArrayStack() {
23+
this(10);
24+
}
25+
26+
public ArrayStack(int capacity) {
27+
if (capacity < 0) {
28+
throw new IllegalArgumentException("Illegal Capacity: " + capacity);
29+
}
30+
31+
mData = new int[capacity];
32+
}
33+
34+
public int push(int item) {
35+
if (mSize == mData.length) {
36+
throw new IllegalArgumentException("Stack full");
37+
}
38+
39+
mData[mSize++] = item;
40+
return item;
41+
}
42+
43+
public int pop() {
44+
if (mSize == 0) {
45+
throw new IllegalArgumentException("Stack empty");
46+
}
47+
48+
int obj = mData[mSize - 1];
49+
mSize--;
50+
51+
return obj;
52+
}
53+
54+
public int peek() {
55+
if (mSize == 0) {
56+
throw new IllegalArgumentException("Stack empty");
57+
}
58+
59+
return mData[mSize - 1];
60+
}
61+
62+
public boolean empty() {
63+
return size() == 0;
64+
}
65+
66+
public int size() {
67+
return mSize;
68+
}
69+
70+
}
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
package com.fantasy.datastructure.stack.test;
2+
3+
import com.fantasy.datastructure.stack.ArrayStack;
4+
5+
/**
6+
* “顺序栈”的测试类
7+
*
8+
* <pre>
9+
* author : Fantasy
10+
* version : 1.0, 2020-08-30
11+
* since : 1.0, 2020-08-30
12+
* </pre>
13+
*/
14+
public class ArrayStackTest {
15+
16+
public static void main(String[] args) {
17+
ArrayStack stack = new ArrayStack();
18+
stack.push(1);
19+
stack.push(2);
20+
stack.push(3);
21+
stack.push(4);
22+
stack.push(5);
23+
System.out.println(stack.pop());
24+
System.out.println(stack.peek());
25+
System.out.println("size : " + stack.size());
26+
}
27+
28+
}

0 commit comments

Comments
 (0)