这段代码完成的功能是实现一个简单的单向链表,可以通过操作任意增加一个节点,此节点自动放在最后一个节点之后。能够
通过方法,可以自动的将全部的节点输出,可以查找一个节点是否存在,可以删除一个节点。我想问下高手private Node root ; // 要定义出根节点这样定义出来的是所谓的根节点是Node类的属性,还是一个实例?代码里反复出现的this.root指的是什么?是代表根节点这
个对象吗?为什么可以代表呢?(我是菜鸟,请高手能帮我讲的详细点,万分万分感谢)
class Link{
class Node{
private String name ; // 保存节点的名字
private Node next ; // 保存下一个节点
public Node(String name){
this.name = name ;
}
public String getName(){
return this.name ;
}
public void addNode(Node newNode){
if(this.next==null){ // 后面没有东西
this.next = newNode ;
}else{
this.next.addNode(newNode) ; // 向下继续查
}
}
public void printNode(){
System.out.print(this.name + " --> " ) ;
if(this.next!=null){
this.next.printNode() ; // 向下继续列出
}
}
public boolean searchNode(String name){
if(this.name.equals(name)){
return true ;
}else{
if(this.next!=null){
return this.next.searchNode(name) ;
}else{
return false ;
}
}
}
public void deleteNode(Node preNode,String name){
if(this.name.equals(name)){
preNode.next = this.next ;
}else{
this.next.deleteNode(this,name) ;
}
}
};
private Node root ; // 要定义出根节点
public void add(String name){
Node newNode = new Node(name) ;
if(this.root==null){ // 没有根节点,则把第一个作为根节点
this.root = newNode ;
}else{
this.root.addNode(newNode) ;
}
}
public void print(){
if(this.root!=null){
this.root.printNode() ;
}
}
public boolean search(String name){ // 指定查找的名字
if(this.root!=null){
return this.root.searchNode(name) ;
}else{
return false ;
}
}
public void delete(String name){
if(this.search(name)){ // 判断此节点是否存在
if(this.root.name.equals(name)){
if(this.root.next!=null){
this.root = this.root.next ; // 改变根节点
}else{
this.root = null ; // 取消
}
}else{
if(this.root.next!=null){
this.root.next.deleteNode(root,name) ;
}
}
}
}
};
public class LinkDemo02{
public static void main(String args[]){
Link link = new Link() ;
link.add("根节点") ;
link.add("第一节点") ;
link.add("第二节点") ;
link.add("第三节点") ;
link.add("第四节点") ;
link.add("第五节点") ;
link.print() ;
System.out.println() ;
System.out.println(link.search("第x节点")) ;
link.delete("第四节点") ;
link.delete("根节点") ;
link.print() ;
}
};

解决方案 »

  1.   

    private Node root ;
    只是定义了一个Node类型的引用,改引用现在没有指向任何对象,是一个null,当你创建一个Node对象时,可以把这个Node对象的地址赋值给这个root
    this.root就是指你刚定义的root
    引用时指向对象的,对引用的操作是通过对对象发送消息实现的,所以操作引用实际上就是操作引用指向的对象
      

  2.   

    private Node root ;
    只是定义了一个Node类型的引用,改引用现在没有指向任何对象,是一个null,当你创建一个Node对象时,可以把这个Node对象的地址赋值给这个root
    this.root就是指你刚定义的root
    引用时指向对象的,对引用的操作是通过对对象发送消息实现的,所以操作引用实际上就是操作引用指向的对象====
    谢谢大人的回答,我还想问下捏那在上面的那段代码里,那个root这个引用 指向的是哪个对象啊 是private Node root ; // 要定义出根节点
    public void add(String name){
    Node newNode = new Node(name) ;
    if(this.root==null){ // 没有根节点,则把第一个作为根节点
    this.root = newNode ;
    }else{
    this.root.addNode(newNode) ;
    }
    }里面的的newNode对象吗?
      

  3.   

    newNode不是个对象
    Node newNode = new Node(name)
    newNode是指向对象new Node(name)的一个引用,该引用记录的是这个对象的地址
    if(this.root==null){
    this.root = newNode 
    }
    如果root为null,就把newNode的值赋给root,也就是现在root也指向new Node(name)了