1 package com.xt.test;
 2 
 3 /**
 4  * 泛型实现堆栈,thinking in java中的例子
 5  * 
 6  * @author Administrator
 7  *
 8  * @param <T>
 9  */
10 public class LinkedTrack<T> {
11     private static class Node<U> {
12         U item;
13         Node<U> next;
14 
15         Node() {
16             item = null;
17             next = null;
18         }
19 
20         Node(U item, Node<U> next) {
21             this.item = item;
22             this.next = next;
23         }
24 
25         boolean end() {
26             return item == null && next == null;
27         }
28     }
29 
30     /**
31      * 末端哨兵,用来标示是否到了尽头
32      */
33     private Node<T> top = new Node<T>();
34 
35     /**
36      * 节点中添加节点(包含进去)
37      * 
38      * @param item
39      */
40     public void push(T item) {
41         top = new Node<T>(item, top);
42     }
43 
44     /**
45      * 节点中取节点(舍去)
46      * 
47      * @return
48      */
49     public T pop() {
50         T result = top.item;
51         if (!top.end())
52             top = top.next;
53         return result;
54     }
55 
56     public static void main(String[] args) {
57         LinkedTrack<String> lt = new LinkedTrack<String>();
58         for (String s : "This is a test!".split(" "))
59             lt.push(s);
60         String s;
61         while ((s = lt.pop()) != null)
62             System.out.println(s);
63     }
64 
65 }

看书中的代码看了很久都搞不懂到底是怎么实现的,最终在eclipse中把代码照着写了一边,人笨,调试运行才恍然大悟原来用了<多层嵌套的原理>(自己瞎想的名字),具体看如下截图: