题目描述:
标签:哈希表 链表
请实现 copyRandomList 函数,复制一个复杂链表。在复杂链表中,每个节点除了有一个 next 指针指向下一个节点,还有一个 random 指针指向链表中的任意节点或者 null。
代码:
思路分析:
分三步走:
① 复制节点,并连接到每个对应的节点后面
② 建立random连接
③ 拆分
/*
// Definition for a Node.
class Node {
int val;
Node next;
Node random;
public Node(int val) {
this.val = val;
this.next = null;
this.random = null;
}
}
*/
class Solution {
public Node copyRandomList(Node head) {
if(head == null){
return null;
}
Node cur = head;
//插入新节点(即复制节点)
while(cur != null){
Node clone = new Node(cur.val);
clone.next = cur.next;
cur.next = clone;
cur = clone.next;
}
//建立random连接
cur = head;
while(cur != null){
Node clone = cur.next;
if(cur.random != null){
clone.random = cur.random.next;
}
cur = clone.next;
}
//拆分
cur = head;
Node cloneHead = head.next;
while(cur.next != null){
Node next = cur.next;
cur.next = next.next;
cur = next;
}
return cloneHead;
}
}