File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ package datastructure ;
2+
3+ /**
4+ * 使用Java泛型实现栈
5+ *
6+ * @author liuyuning
7+ *
8+ * @param <T>
9+ */
10+ public class Stack <T > {
11+
12+ private static class Node <U > {
13+ private U value ;
14+ private Node <U > next ;
15+
16+ public Node () {
17+ value = null ;
18+ next = null ;
19+ }
20+
21+ public Node (U value , Node <U > next ) {
22+ this .value = value ;
23+ this .next = next ;
24+ }
25+
26+ /**
27+ * 判断栈是否为空
28+ *
29+ * @return true 如果为空;否则,false
30+ */
31+ public boolean empty () {
32+ return value == null && next == null ;
33+ }
34+ }
35+
36+ /**
37+ * 定义栈顶元素
38+ */
39+ private Node <T > top = new Node <T >();
40+
41+ /**
42+ * 入栈操作
43+ *
44+ * @param value
45+ * 入栈元素的值
46+ */
47+ public void push (T value ) {
48+ top = new Node <T >(value , top );
49+ }
50+
51+ /**
52+ * 出栈操作
53+ *
54+ * @return 栈顶元素的值
55+ */
56+ public T pop () {
57+ T value = top .value ;
58+ if (!top .empty ()) {
59+ top = top .next ;
60+ }
61+ return value ;
62+ }
63+
64+ public static void main (String [] args ) {
65+ Stack <String > stack = new Stack <String >();
66+ String string = "This is a test for stack" ;
67+
68+ System .out .println ("入栈元素(String)依次为:" );
69+ for (String nodeIn : string .split (" " )) {
70+ stack .push (nodeIn );
71+ System .out .println (nodeIn );
72+ }
73+
74+ System .out .println ("出栈元素(String)依次为:" );
75+ String nodeOut ;
76+ while ((nodeOut = stack .pop ()) != null ) {
77+ System .out .println (nodeOut );
78+ }
79+ }
80+ }
Load diff This file was deleted.
You can’t perform that action at this time.
0 commit comments