//类型参数不能用基本类型,t和u其实是同一类型。
//每次放新数据都成为新的top,把原来的top往下压一级,通过指针建立链接。
//末端哨兵既是默认构造器创建出的符合end()返回true的节点。
//: generics/linkedstack.java // a stack implemented with an internal linked structure. package generics; public class linkedstack<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>(); // end sentinel public void push(t item) { top = new node<t>(item, top); } public t pop() { t result = top.item; if(!top.end()) top = top.next; return result; } public static void main(string[] args) { linkedstack<string> lss = new linkedstack<string>(); for(string s : "phasers on stun!".split(" ")) lss.push(s); string ss; while((ss = lss.pop()) != null) system.out.println(ss); //----- if put integer into the linkedlist linkedstack<integer> lii = new linkedstack<integer>(); for(integer i = 0; i < 10; i++){ lii.push(i); } integer end; while((end = lii.pop()) != null) system.out.println(end); //----- integer test end! } } /* output: stun! on phasers */
更多java编程思想里的泛型实现一个堆栈类。