开发者

Deep copy of linear linked list

开发者 https://www.devze.com 2023-02-04 10:47 出处:网络
I have a linear linked list that consists of nodes: class Node{ Object data; Node link; public Node(Object pData, Node pLink){

I have a linear linked list that consists of nodes:

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

I want to make a deep copy of a list. Then increment each node of the original list and p开发者_如何学Pythonrint both. I do not know if the code is right.

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

...gives me just 123 for the second println but something is wrong with the copy. Any ideas?

Update:

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


A deep copy would imply that you need to do a copy of data also.

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

So you need to decide how you are going to copy the object.

EDIT: You can use something like the Deep Cloning Library to help. They use reflection etc. If you know the type of objects in that you are creating the class of objects yourself you can create a copy constructor.


Well, judging from the fact that link could be null, you may wish to avoid calling this.link.copy() without checking first. I am guessing the problem you are talking about is a null pointer exception.

EDIT:

Yeah, and what Vincent said. :)

Be sure to copy the object as well.

0

精彩评论

暂无评论...
验证码 换一张
取 消