原来代码是:
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 s; while((s = lss.pop()) != null) System.out.println(s); }}去掉Node类上的类型参数,内部类可以访问其外部类的类型参数,即原来是嵌套(静态)内部类,现在要修改为成员内部类即可,具体如下:public class LinkedStack<T> { private class Node{ T item; Node next; Node(){ item = null; next = null; } Node(T item, Node next){ this.item = item; this.next = next; } boolean end(){ return (item == null) && (next==null); } } private Node top = new Node(); public void push(T item){ top = new Node(item, top); } public T top(){ 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 s; while ((s=lss.top())!= null){ System.out.println(s); } }}
新闻热点
疑难解答