[尝试编写带有自定义链接列表的自定义(但众所周知)的堆栈通用实现。但是算法不是重点。我的问题是,为什么不需要参数化
class Node<T>
以及声明
Node <T> top; //pointer to next node
会多余吗?为什么?或者可能需要使用其他字符,例如
<U>
?
public class Stack<T> {
//T is the type parameter
Node top; //topmost element of stack
//defines each node of stack
class Node{
T value; //value of each node
Node next; //pointer to next node
public Node(T value){
this.value=value; //initializing
next=null;
}
}
//This function pushes new element
public void push(T value){
Node current=new Node(value);
if(isEmpty())
top=current; //if empty stack
else{
current.next=top;
top=current;
}
}
//This function pops topmost element
public T pop(){
T value=null;
if(!isEmpty()){
top=top.next;
value=top.value;
}
return value; //returning popped value
}
[尝试编写带有自定义链接列表的自定义(但众所周知)的堆栈通用实现。但是算法不是重点。我的问题是,为什么不需要参数化类Node
注意,这里的Node
类不是static
。这意味着Stack
的每个instance
如果您的Node类是其自己的顶级类(在其自己的.java文件中,则它需要一个通用参数,如您期望的那样)。我建议您这样做。
会多余吗?