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.
Example 1:
Input:
{“KaTeX parse error: Expected '}', got 'EOF' at end of input: …":"1","next":{"id”:“2”,“next”:null,“random”:{“KaTeX parse error: Expected 'EOF', got '}' at position 9: ref":"2"}̲,"val":2},"rand…ref”:“2”},“val”:1}
Explanation:
Node 1’s value is 1, both of its next and random pointer points to Node 2.
Node 2’s value is 2, its next pointer points to null and its random pointer points to itself.
Note:
You must return the copy of the given head as a reference to the cloned list.
分析:
一个链表的拷贝,但是和普通链表不同的是每个节点多了一个指向任意节点或者为空的指针。但是我们在拷贝链表的时候如何将这个随机的指向拷贝下来呢?我们将复制的节点放在被拷贝节点之后,第一遍拷贝时只拷贝对应的值,第二次遍历再将上一个节点的随机指针,拷贝给下一个节点。第三步将合并的链表拆为两个单链表。
/*
// Definition for a Node.
class Node {
public int val;
public Node next;
public Node random;
public Node() {}
public Node(int _val,Node _next,Node _random) {
val = _val;
next = _next;
random = _random;
}
};
*/
class Solution {
public Node copyRandomList(Node head) {
for (Node cur = head; cur != null; ) {
Node node = new Node();
node.val = cur.val;
node.next = cur.next;
cur.next = node;
cur = node.next;
}
for (Node cur = head; cur != null; ) {
if (cur.random != null)
cur.next.random = cur.random.next;
cur = cur.next.next;
}
// 分拆两个单链表
Node dummy = new Node(-1);
for (Node cur = head, new_cur = dummy;
cur != null; ) {
new_cur.next = cur.next;
new_cur = new_cur.next;
cur.next = cur.next.next;
cur = cur.next;
}
return dummy.next;
}
}