標籤:
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 item39 */40 public void push(T item) {41 top = new Node<T>(item, top);42 }43 44 /**45 * 節點中取節點(捨去)46 * 47 * @return48 */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中把代碼照著寫了一邊,人笨,調試運行才恍然大悟原來用來<多層嵌套的原理>(自己瞎想的名字),具體看如下:
JAVA泛型實現一個堆棧類