日期:2014-05-20  浏览次数:20608 次

java递归中对象实例化的问题
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); 这种递归怎样保存第三次的节点对象????
  }


------解决方案--------------------
单向链表。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方法所以能一直传递下去。