File tree Expand file tree Collapse file tree 2 files changed +128
-0
lines changed
junit/com/ikook/basic_data_structure
src/com/ikook/basic_data_structure Expand file tree Collapse file tree 2 files changed +128
-0
lines changed Original file line number Diff line number Diff line change
1
+ package com .ikook .basic_data_structure ;
2
+
3
+ import static org .junit .Assert .*;
4
+
5
+ import java .util .Date ;
6
+
7
+ import org .junit .Before ;
8
+ import org .junit .Test ;
9
+
10
+ /**
11
+ * 此单元测试只测试了正常情况,一些异常情况没有测试。
12
+ * @author ikook
13
+ */
14
+ public class MyStackTest {
15
+
16
+ private MyStack stack ;
17
+
18
+ @ Before
19
+ public void setUp () {
20
+ stack = new MyStack ();
21
+ stack .push (111 );
22
+ stack .push ("222" );
23
+ stack .push (333 );
24
+ stack .push (new Date ());
25
+ stack .push ("555" );
26
+ }
27
+
28
+ @ Test
29
+ public void testPush () {
30
+ stack .push (93554 );
31
+ assertEquals (6 , stack .size ());
32
+ }
33
+
34
+ @ Test
35
+ public void testPop () {
36
+ assertEquals ("555" , stack .pop ());
37
+ assertEquals (4 , stack .size ());
38
+
39
+ assertEquals (new Date (), stack .pop ());
40
+ }
41
+
42
+ @ Test
43
+ public void testGetTop () {
44
+ assertEquals ("555" , stack .getTop ());
45
+ }
46
+
47
+ @ Test
48
+ public void testIsEmpty () {
49
+ assertEquals (false , stack .isEmpty ());
50
+
51
+ MyStack stack = new MyStack ();
52
+ assertEquals (true , stack .isEmpty ());
53
+ }
54
+
55
+ }
Original file line number Diff line number Diff line change
1
+ package com .ikook .basic_data_structure ;
2
+
3
+ /**
4
+ * @author ikook; QQ号码: 935542673
5
+ */
6
+ public class MyStack {
7
+
8
+ private MyArrayList elementDate = new MyArrayList ();
9
+
10
+ /**
11
+ * 入栈操作
12
+ * @param obj
13
+ */
14
+ public void push (Object obj ) {
15
+ elementDate .add (obj );
16
+ }
17
+
18
+ /**
19
+ * 出栈操作
20
+ * @return
21
+ */
22
+ public Object pop () {
23
+ emptyExce ();
24
+ return elementDate .remove (topIndex ());
25
+ }
26
+
27
+ /**
28
+ * 获取栈顶元素
29
+ * @return
30
+ */
31
+ public Object getTop () {
32
+ emptyExce ();
33
+ return elementDate .get (topIndex ());
34
+ }
35
+
36
+ /**
37
+ * 判断栈是否为空
38
+ * @return
39
+ */
40
+ public boolean isEmpty () {
41
+ return size () == 0 ;
42
+ }
43
+
44
+ /**
45
+ * 获取栈的深度
46
+ * @return
47
+ */
48
+ public int size () {
49
+ return elementDate .size ();
50
+ }
51
+
52
+ /**
53
+ * 栈顶元素所在索引封装类
54
+ * @return
55
+ */
56
+ private int topIndex () {
57
+ return size () - 1 ;
58
+ }
59
+
60
+ /**
61
+ * 队列为空异常处理封装类
62
+ */
63
+ private void emptyExce () {
64
+ if (isEmpty ()) {
65
+ try {
66
+ throw new Exception ("队列为空" );
67
+ } catch (Exception e ) {
68
+ e .printStackTrace ();
69
+ }
70
+ }
71
+ }
72
+
73
+ }
You can’t perform that action at this time.
0 commit comments