剑指 Offer 35. 复杂链表的复制
由题意可知,链表中每个节点可以用一个 [val, random_index] 表示:
val:一个表示 Node.val 的整数。
random_index:随机指针指向的节点索引(范围从 0 到 n-1);如果不指向任何节点,则为 null 。
链表的复制过程可分为两步:第一步是复制原始链表上的每个节点,并用next指针相连; 第二步是设置每个节点的random指针。
—————————————————————————————————————
思路:哈希表
新建一个哈希表map
第一步复制节点值:将原始链表上的每个节点 cur复制为cur’,然后把<cur,cur’>的配对信息放到map中;
第二步设置每个节点的next和random指针:将复制节点cur’的next指向同结点cur的next指向。如果在原始链表中节点cur的random指针指向节点 S,那么在复制链表中,对应的 cur’节点应该指向 S’。
class Solution {
public Node copyRandomList(Node head) {
HashMap<Node, Node> map = new HashMap<>();
Node cur = head;
if (head == null) {
return null;
}
while (cur != null) {
map.put(cur, new Node(cur.val));
cur = cur.next;
}
cur = head;
while (cur != null) {
map.get(cur).next = map.get(cur.next);
map.get(cur).random = map.get(cur.random);
cur = cur.next;
}
return map.get(head);
}
}
思路:原地修改
(1)复制每一个节点,使得复制后的节点都在当前节点的下一个节点,如 1 -> 2 -> 3 -> null ,复制完就是 1 -> 1 -> 2 -> 2 -> 3 - > 3 -> null;
(2)从头开始遍历链表,原生链表的节点的指向任意节点,使复制的节点也都指向某一任意节点。先判断 cur.random 是否存在,然后通过 cur.next.random = cur.random.next 可以将复制节点的随机指针串起来;
(3)将复制完的链表一分为二,即把原生节点重新连接起来,把复制后的节点连接起来。
class Solution {
public Node copyRandomList(Node head) {
if (head == null) {
return null;
}
//复制节点
Node cur = head;
while (cur != null) {
Node copy = new Node(cur.val);
copy.next = cur.next;
cur.next = copy;
cur = cur.next.next;
}
//指定随机指针
cur = head;
while (cur != null) {
if (cur.random != null) {
cur.next.random = cur.random.next;
}
cur = cur.next.next;
}
//重新连接链表
Node copyHead = head.next;
cur = head;
Node curCopy = head.next;
while (cur != null) {
cur.next = cur.next.next;
cur = cur.next;
if (curCopy.next != null) {
curCopy.next = curCopy.next.next;
curCopy = curCopy.next;
}
}
return copyHead;
}
}