0

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

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

2 回答 2

3

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

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

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

编辑:您可以使用像Deep Cloning Library这样的东西来提供帮助。他们使用反射等。如果您知道自己创建对象类的对象类型,则可以创建一个复制构造函数。

于 2011-01-13T21:58:51.430 回答
1

好吧,从链接可能为空的事实来看,您可能希望避免在不先检查的情况下调用 this.link.copy() 。我猜您正在谈论的问题是空指针异常。

编辑:

是的,正如文森特所说。:)

一定要复制对象。

于 2011-01-13T21:57:47.137 回答