package Lang_1;
class Link
{  
  class Node
   { private String data;
    private Node next;
    public Node(String data)
     { this.data=data;
      }
    public void add(Node nextNode)
      { if(this.next==null)
        { this.next=nextNode;
    
         }
        else
         { this.next.add(nextNode);
         }
       } 
    public void print()
     {  System.out.print(this.data+"\t");
        if(this.next!=null)
         { this.next.print();
         }
      }
  
   } private Node root;
 public void add(String data)
 { Node newNode=new Node(data);
if(this.root==null)
 { this.root=newNode;
 }
else
 {
this.root.add(newNode);
 }
 }
public void printNode()
{ if(this.root!=null)
   { this.root.print();

   }
}
}public class LinkNode 
{   public static void main(String[] args) 
{
   Link link=new Link();
   link.add("A");
   link.add("B");
   link.add("C");
   link.printNode(); }}上面的程序是模拟链式存储,通过递归调用,添加.打印数据。在Link对象中创建一个内部类Node,这儿当我实例化Link对象,三次调用add()方法,每次调用add()方法,Node都会实例化一次。link第三次添加数据,在内部类Node中,else
         { this.next.add(nextNode); 这种递归怎样保存第三次的节点对象????
         }

解决方案 »

  1.   

    单向链表。link.add("C")
    第一次
    public void add(String data){
    Node newNode = new Node(data);
    if (this.root == null) {
    this.root = newNode;
    } else {
    this.root.add(newNode);
    }
    }
    不满足,root!=null,跳到this.root.add(newNode);
    public void add(Node nextNode) {
    if (this.next == null){
    this.next = nextNode; } else {
    this.next.add(nextNode);
    }
    }
    root.next!=null.跳刀this.next.add(nextNode);此时this.next变成了b这个节点,也就是b这个实例的add方法所以能一直传递下去。
      

  2.   


     这儿的link.add("A")执行完后,Node newNode=new Node(data) newNode对象在栈中的引用赋给root之后,newNode会被垃圾回收机制回收,还是怎么回事?因为第二次调用link.add("B"),newNode的地址和第一次实例化的一样,只是内容不一样。方法中的局部变量在方法调用后就失效了。所以第一次的实例化对象newNode和第二次的实例化对象newNode的地址没有同时存储在栈中,可以这样理解吧???