后面的刷题中记得复用指针,节省空间
/**
* https://leetcode-cn.com/problems/copy-list-with-random-pointer/
* 138. 复制带随机指针的链表
*
* @param head
* @return
*/
public static Node copyRandomList(Node head) {
Map<Node, Node> map = new HashMap<>();
Node node = head;
while (node != null) {
map.put(node, new Node(node.val));
node = node.next;
}
node = head;
while (node != null) {
map.get(node).next = map.get(node.next);
map.get(node).random = map.get(node.random);
node = node.next;
}
return map.get(head);
}
/**
* https://leetcode-cn.com/problems/copy-list-with-random-pointer/
* 138. 复制带随机指针的链表
* <p>
* 不用map的方法
*
* @param head
* @return
*/
public static Node copyRandomList2(Node head) {
if (head == null) {
return null;
}
//先将逐步生成新的节点然后串在节点后面
//1->1`->2->2`->null
Node node = head;
Node next;
while (node != null) {
next = node.next;
node.next = new Node(node.val);
node.next.next = next;
node = next;
}
//找到random
node = head;
//不需要分离节点,所以直接用快指针一次跳两步的方法
while (node != null) {
node.next.random = node.random != null ? node.random.next : null;
node = node.next.next;
}
//先把克隆链表头节点记录下来,最后返回
Node result = head.next;
//分离链表
node = head;
Node copyNode;
//需要分离,所以用next记录下一个遍历的节点
while (node != null) {
next = node.next.next;
copyNode = node.next;
node.next = next;
copyNode.next = next != null ? next.next : null;
node = next;
}
return result;
}