回溯
该方法通不过所有的测试用例
/**
* Definition for singly-linked list with a random pointer.
* class RandomListNode {
* int label;
* RandomListNode next, random;
* RandomListNode(int x) { this.label = x; }
* };
*/
import java.util.HashMap;
public class Solution {
//hashmap记录了旧结点
HashMap<RandomListNode,RandomListNode> visitedHash =new HashMap<RandomListNode,RandomListNode>();
public RandomListNode copyRandomList(RandomListNode head) {
if(head==null)
return null;
//如果已经访问过,直接获取
if(this.visitedHash.containsKey(head)){
return this.visitedHash.get(head);
}
//如果没有访问过,新建一个新节点与旧结点的值一样
RandomListNode node=new RandomListNode(head.label);
this.visitedHash.put(head,node);
//复制next,random
node.next=this.copyRandomList(node.next);
node.random=this.copyRandomList(node.random);
return node;
}
}
空间复杂度o(N)
import java.util.HashMap;
/**
* 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 {
HashMap<RandomListNode,RandomListNode> visitedHash =new HashMap<RandomListNode,RandomListNode>();
//克隆节点
public RandomListNode getclonedNode(RandomListNode node) {
if (node!= null){
//如果已经访问过,直接获取
if (this.visitedHash.containsKey(node)) {
return this.visitedHash.get(node);
} else {
//如果没有访问过,
this.visitedHash.put(node, new RandomListNode(node.label));
return this.visitedHash.get(node);
}
}
return null;
}
public RandomListNode copyRandomList(RandomListNode head) {
if(head==null){
return null;
}
RandomListNode oldNode=head;
//创建新节点
RandomListNode newNode=new RandomListNode(oldNode.label);
this.visitedHash.put(oldNode,newNode);
//克隆next,random
while(oldNode!=null){
newNode.next=this.copyRandomList(oldNode.next);
newNode.random=this.getclonedNode(oldNode.random);
oldNode=oldNode.next;
newNode=newNode.next;
}
return this.visitedHash.get(head);
}
}
o(1)
思想:先复制节点,将其插入到原链表后,改变random,分离新旧链表
/**
* 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) {
if (head == null) {
return null;
}
RandomListNode ptr = head;
//复制节点,将其插入到原链表后
while (ptr != null) {
RandomListNode newNode = new RandomListNode(ptr.label);
newNode.next = ptr.next;
ptr.next = newNode;
ptr = newNode.next;
}
ptr = head;
//改变random,
while (ptr != null) {
ptr.next.random = (ptr.random != null) ? ptr.random.next : null;
ptr = ptr.next.next;
}
//分离新旧链表
RandomListNode ptr_old_list = head; // A->B->C
RandomListNode ptr_new_list = head.next; // A'->B'->C'
RandomListNode head_old = head.next;
while (ptr_old_list != null) {
ptr_old_list.next = ptr_old_list.next.next;
ptr_new_list.next = (ptr_new_list.next != null) ? ptr_new_list.next.next : null;
ptr_old_list = ptr_old_list.next;
ptr_new_list = ptr_new_list.next;
}
return head_old;
}
}