在leetcode上浏览我想尝试这个问题:给出一个链表,每个节点都包含一个额外的随机指针,可以指向列表中的任何节点或null。 返回列表的深层副本。但是,我的代码似乎有一个错误,因为它没有通过评分者而且没有告诉我原因。
我的代码分为3个阶段。
/**
* 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;
}
}
答案 0 :(得分:0)
不要在最后current = current.next.next
跳过太远 - 你已经将current.next
分配给current.next.next
(这是下一个原始节点),所以我认为最后一个循环中的最后一行应该是current = current.next
?