ノードで構成される線形リンクリストがあります。
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());
}
}
... 2番目の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);
}
}