【问题标题】:How to clone a double linked list using recursivity如何使用递归克隆双向链表
【发布时间】:2014-10-23 16:31:37
【问题描述】:

我正在尝试实现一种克隆双链表的方法。我正在尝试根据要求进行递归。

我认为它克隆正确,但是当我尝试将另一个元素添加到列表末尾时,它被添加到原始队列而不是克隆。

这是我调用方法并进行克隆的主要部分:

    doublelinkedlist<Integer> aux=new doublelinkedlist<Integer>();
    doublelinkedlist<Integer> aux2=new doublelinkedlist<Integer>();
    aux.addRight(10);
    aux.addRight(11);
    aux.addRight(9);
    aux.addRight(12);
    //aux2.addRight(12);
    aux2 = (doublelinkedlist<Integer>) aux.clone();
    aux2.RemoveRight();
    System.out.println("Original Queue: "+aux.toString());
    System.out.println("Copy queue: "+aux2.toString());

这是DoubleLinkedList的克隆方法:

public Object clone(){
    doublelinkedlist copia = null;
    try{
        copia = (doublelinkedlist)super.clone();

        if (left != null){
            copia.left = (node<E>)left.clone();
        }
    }catch (CloneNotSupportedException e){
        return null;
    }
    return copia;
}

这是节点类的克隆:

    public Object clone(){
        node<E> copia = null;
        try{
            copia = (node<E>)(super.clone());

            if (next != null){
                copia.next = (node<E>)(next.clone());
                copia.prev = copia;
            }

        }catch (CloneNotSupportedException e){
            return null;
        }
        return copia;
    }

【问题讨论】:

  • 您的问题找到解决方案了吗?

标签: java recursion linked-list clone nodes


【解决方案1】:

错误在以下行:

copia = (doublelinkedlist)super.clone();

来自JavaDocs of Object#clone()

按照惯例,这个方法返回的对象应该是 独立于这个对象(正在被克隆)。为达到这个 独立性,可能需要修改一个或多个字段 super.clone 在返回之前返回的对象。

现在是重要的部分:

通常,这 意味着复制任何包含内部“深 被克隆的对象的结构”并替换对 这些对象与副本的引用。

[...]
因此,此方法执行此对象的“浅拷贝”,而不是 “深拷贝”操作。

您并没有深度复制您的对象,您只是获得了对它们的新引用。

【讨论】:

  • 我不太明白,在我的情况下,我应该写什么来做一个深拷贝?
【解决方案2】:

您可以使用Collections.copy(dest, src); 克隆列表。 这是一个具有递归性的克隆示例

public class ClonableLinkedList extends LinkedList<Double> {
    public static void main(String[] args) {
        ClonableLinkedList clonable = new ClonableLinkedList();
        for (int i = 0; i < 50; i++) {
            clonable.add(new Random().nextDouble());
        }
        LinkedList<Double> cloned = clonable.clone();
        for (int i = 0; i < 50; i++) {
            System.out.println(String.format("List1 = %f, List2 = %f", clonable.get(i), cloned.get(i)));
        }
    }

    public LinkedList<Double> clone() {
        LinkedList<Double> list = new LinkedList<Double>();
        return cloneElements(list, 0);
    }

    private LinkedList<Double> cloneElements(LinkedList<Double> list, int index) {
        list.add(this.get(index++));
        if (index < this.size()) {
            return cloneElements(list, index);
        } else {
            return list;
        }
    }
}

【讨论】:

  • 如果是这样的话,我应该实现克隆方法,但无论如何谢谢
猜你喜欢
  • 2023-04-03
  • 2017-05-16
  • 2016-08-01
  • 2017-08-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-04-15
  • 2015-07-07
相关资源
最近更新 更多