A linked list is given such that each node contains an additional random pointer which could point to any node in the list or null.
Return a deep copy of the list.
与图拷贝的方法类似,使用map的方式进行处理,但是也有不同,图拷贝是线拷贝点,然后是边;链表可以直接在一个循环中统一处理。
java
/**
* 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 head;
}
Map<RandomListNode, RandomListNode> map = new HashMap<>();
RandomListNode dummy = new RandomListNode(0);
RandomListNode pre = dummy;
RandomListNode node;
while (head != null) {
if (map.containsKey(head)) {
node = map.get(head);
} else {
node = new RandomListNode(head.label);
map.put(head, node);
}
pre.next = node;
if (head.random != null) {
if (map.containsKey(head.random)) {
node.random = map.get(head.random);
} else {
node.random = new RandomListNode(head.random.label);
map.put(head.random, node.random);
}
}
pre = pre.next;
head = head.next;
}
return dummy.next;
}
}
python
# Definition for singly-linked list with a random pointer.
# class RandomListNode(object):
# def __init__(self, x):
# self.label = x
# self.next = None
# self.random = None
class Solution(object):
def copyRandomList(self, head):
"""
:type head: RandomListNode
:rtype: RandomListNode
"""
if head is None:
return head
mapping = {}
dummy = RandomListNode(0)
pre, node = dummy, head
while head is not None:
if head in mapping:
node = mapping[head]
else:
node = RandomListNode(head.label)
mapping[head] = node
pre.next = node
if head.random is not None:
if head.random in mapping:
node.random = mapping[head.random]
else:
node.random = RandomListNode(head.random.label)
mapping[head.random] = node.random
pre = pre.next
head = head.next
return dummy.next