我有一个由节点组成的线性链表:
class Node{
Object data;
Node link;
public Node(Object pData, Node pLink){
this.data = pData;
this.link = pLink;
}
public String toString(){
if(this.link != null){
return this.data.toString() + this.link.toString();
}else{
return this.data.toString() ;
}
}
public void inc(){
this.data = new Integer((Integer)this.data + 1);
}
public Node copy(){
return new Node(this.data, this.link.copy());
}
}
我想制作一个列表的深层副本。然后递增原始列表的每个节点并打印两者。我不知道代码是否正确。
class Aufg1{
public static void main(String args[]){
Node node3 = new Node(new Integer(3), null);
Node node2 = new Node(new Integer(2), node3);
Node node1 = new Node(new Integer(1), node2);
System.out.println(node1.copy().toString());
System.out.println(node1.toString());
}
}
...第二次 println 只给我 123,但副本有问题。有任何想法吗?
更新:
public Node copy(){
if(this.link != null){
return new Node(new Integer((Integer)this.data), this.link.copy());
}else{
return new Node(new Integer((Integer)this.data), null);
}
}