java - 新列表中链表的重复项

标签 java algorithm data-structures

我正在尝试深入复制节点列表。 例如我的列表如下:

Node n = new Node(1,new Node(12, new Node(34, new Node(3, Node.NIL))));

我的功能是:

    public Node copy() {

       Node initial= this;
       Node duplicate=new Node(initial.getItem());

       while(Node.NIL!=initial.getNext()){

           initial=initial.getNext();
           Object a = initial.getItem();
           duplicate.next=new Node(a);
       }

       return duplicate;
    } 

所以当我这样做时,输出列表是重复的 [1,3]。我不明白 12 和 34 在哪里。

最佳答案

在这一步 duplicate.next=new Node(a); 中,您每次都会覆盖 duplicate.next 的先前值。创建下一个节点时,您应该在每一步更改对 duplicate 的引用。

您可以使用递归来创建下一个节点的副本并在之后创建新节点:

    public Node copy() {
        Node initial= this;
        Node copyNext = this.getNext() == NIL? NIL : this.getNext().copy();
        Node duplicate = new Node(initial.getItem());
        duplicate.next = copyNext;
        return duplicate;
    }

并且没有递归:

    public Node copy() {

        Node currentNode= this;
        Node firstDuplicate = new Node(currentNode.getItem()); //save reference for first node to return
        Node currentDuplicate=firstDuplicate;

        while(Node.NIL!=currentNode.getNext()){
            Node nextNode = currentNode.getNext();
            Node nextCopy = new Node(nextNode.getItem()); //create copy of next
            currentDuplicate.next = nextCopy; //assign this copy as next for current duplicated node
            currentDuplicate = nextCopy; //change reference for current duplicated node to copy 
            currentNode = nextNode; 
        }

        return firstDuplicate;
    }

如果我没理解错的话,您需要创建还原列表。在这种情况下,您不需要创建初始列表的新副本。

    public Node reverse() {
        Node head = NIL; //initial we have a empty list

        Node current = this; //set cursor to current node

        while (current != NIL) {
            Node copy = new Node(current.getItem()); //create a copy of current node
            copy.next = head; //set head node as next for copy 
            head = copy; //now move head to copy 
            current = current.next; // move cursor for next position
        }

        return head;
    }

要使用递归创建反向列表,您只需要额外的方法来保留对先前创建的副本的引用:

    public Node reverse() {
        if (this == NIL) {
            return NIL;
        }

        return reverse(new Node(this.getItem(), NIL), this.getNext());
    }

    private Node reverse(Node head, Node tail) {
        Node copy = new Node(tail.getItem()); 
        copy.next = head;
        if (tail.getNext() == NIL) {
            return copy;
        }
        return reverse(copy, tail.next);
    }

关于java - 新列表中链表的重复项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42116702/

相关文章:

list - 关于映射和泛型的混淆

java - Java中压缩和解压缩字符串的程序

java - 使用spring data优化mongodb的计数

java - 查找数组中 k 个最小数字的索引的算法

java - 如何识别图像文件中的文本以及如何阅读该文本?

algorithm - 找到最大簇的最小值?

java - 使用 Active Objects ORM for Java 的经验?

java - 从 Android 中的 ListView 适配器中删除参数错误

从一组点构建图表的算法

arrays - 索引和小于 K 的网格中的点数