
正文
JAVA泛型实现一个堆栈类
提示:扫一扫查出行【扫一扫了解最新限行尾号】
复制提示
package com.xt.test; /**
* 泛型实现堆栈,thinking in java中的例子
*
* @author Administrator
*
* @param <T>
*/
public class LinkedTrack<T> {
private static class Node<U> {
U item;
Node<U> next; Node() {
item = null;
next = null;
} Node(U item, Node<U> next) {
this.item = item;
this.next = next;
} boolean end() {
return item == null && next == null;
}
} /**
* 末端哨兵,用来标示是否到了尽头
*/
private Node<T> top = new Node<T>(); /**
* 节点中添加节点(包含进去)
*
* @param item
*/
public void push(T item) {
top = new Node<T>(item, top);
} /**
* 节点中取节点(舍去)
*
* @return
*/
public T pop() {
T result = top.item;
if (!top.end())
top = top.next;
return result;
} public static void main(String[] args) {
LinkedTrack<String> lt = new LinkedTrack<String>();
for (String s : "This is a test!".split(" "))
lt.push(s);
String s;
while ((s = lt.pop()) != null)
System.out.println(s);
} }

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







