在 leetcode 上冲浪我想尝试这个问题:给出了一个链表,使得每个节点都包含一个额外的随机指针,该指针可以指向列表中的任何节点或 null。返回列表的深层副本。但是,我的代码似乎存在错误,因为它没有通过评分器并且没有告诉我原因。
我的代码有 3 个阶段。
- 我在第一个和第二个节点之间插入新节点,所以..on。
- 我将原始的随机指针复制到复制节点的随机指针。
- 我将这两个列表分开。
你能帮忙吗?谢谢你。
/**
* 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;
}
}