File tree Expand file tree Collapse file tree 3 files changed +104
-0
lines changed
src/com/fantasy/datastructure/stack Expand file tree Collapse file tree 3 files changed +104
-0
lines changed Original file line number Diff line number Diff line change 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 ]
Original file line number Diff line number Diff line change 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+ }
Original file line number Diff line number Diff line change 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+ }
You can’t perform that action at this time.
0 commit comments