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