gpt4 book ai didi

java - 线性链表的深拷贝

转载 作者:行者123 更新时间:2023-12-01 19:20:10 24 4
gpt4 key购买 nike

我有一个由节点组成的线性链表:

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);
}
}

最佳答案

深层复制意味着您还需要复制数据。

 public Node copy(){
return new Node(copy of this.data, this.link.copy());
}

因此您需要决定如何复制对象。

编辑:您可以使用类似 Deep Cloning Library 的内容帮助。它们使用反射等。如果您知道自己正在创建对象类的对象类型,则可以创建复制构造函数。

关于java - 线性链表的深拷贝,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4685727/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com