在LinkedStack类中定义了一个Node静态内部类,根据类加载机制,Node类会在LinkedStack初始化时被加载。
public class LinkedStack<T> {
private static class Node<T>{
T item;
Node<T> next;
Node(){item = null;next=null;}
Node(T item,Node<T> next){
this.item = item;
this.next = next;
}
boolean end(){return item == null && next == null;}
}
//栈顶元素
private Node<T> top = new Node<T>();
public void push(T item){
//把之前的top放到新生成的top的next元素中
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<>();
for(String s:"Phasers on stun!".split(" "))
lss.push(s);
String s;
while ((s = lss.pop())!=null)
System.out.println(s);
}
}
泛型可以这样理解:尖括号<>中的T就是指的变量类型,在使用时将尖括号<>中的实际类型代替到相应类、接口、方法内部到T的地方。对于上面的例子,就是将String代替LinkedStack类内部所有T即可。
本文介绍了一种使用泛型的LinkedStack数据结构实现方法,包括Node静态内部类的定义及栈的基本操作如push和pop。通过具体示例展示了如何使用泛型替代类型参数,使代码更具通用性和灵活性。
288

被折叠的 条评论
为什么被折叠?



