Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/304.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 复制带有随机指针错误的列表?_Java_Linked List_Deep Copy - Fatal编程技术网

Java 复制带有随机指针错误的列表?

Java 复制带有随机指针错误的列表?,java,linked-list,deep-copy,Java,Linked List,Deep Copy,在leetcode上冲浪我想试试这个问题:一个链表是这样给出的,每个节点都包含一个额外的随机指针,它可以指向列表中的任何节点或null。 返回列表的深度副本。然而,我的代码似乎有一个错误,因为它没有通过评分,也没有告诉我为什么 我的代码有三个阶段 我在第一个和第二个节点之间插入新节点,以此类推 我将原始节点的随机指针复制到复制节点的随机指针 我把这两张单子分开 你能帮忙吗?多谢各位 不要在current=current.next.next的末尾跳得太远--您已经将current.next分配给

在leetcode上冲浪我想试试这个问题:一个链表是这样给出的,每个节点都包含一个额外的随机指针,它可以指向列表中的任何节点或null。 返回列表的深度副本。然而,我的代码似乎有一个错误,因为它没有通过评分,也没有告诉我为什么

我的代码有三个阶段

  • 我在第一个和第二个节点之间插入新节点,以此类推
  • 我将原始节点的随机指针复制到复制节点的随机指针
  • 我把这两张单子分开 你能帮忙吗?多谢各位



    不要在
    current=current.next.next
    的末尾跳得太远--您已经将
    current.next
    分配给
    current.next.next
    (下一个原始节点),所以我认为最后一个循环中的最后一行应该是
    current=current.next

    您的右边。而且我也没有在前进。我找到了解决办法。谢谢
    /**
     * Definition for singly-linked list with a random pointer.
     * class RandomListNode {
     *     int label;
     *     RandomListNode next, random;
     *     RandomListNode(int x) { this.label = x; }
     * };
     */
    public class Solution {
        public RandomListNode copyRandomList(RandomListNode head) {
            // Note: The Solution object is instantiated only once and is reused by each test case.
    
            if(head == null) return head;
    
            RandomListNode current = head;
            RandomListNode temp = null;
            RandomListNode solution = null;
            //insertion
            while(current != null){
                RandomListNode clone = new RandomListNode(current.label);
                temp = current.next;
                current.next = clone;
                clone.next = temp;
                current = current.next.next;
            }
    
            //copy random
            current = head;
            while(current != null){
                if(current.random!=null){
                current.next.random = current.random.next;
                }
                current = current.next.next;
            }
    
            //separation
            current = head;
            solution  = current.next;
            while(current != null){
                temp = current.next;
                current.next = current.next.next;
                temp.next = temp.next.next;
                current = current.next.next;
            }
    
            return solution;
        }
    }