复制链表


import java.util.HashMap;

/**
* 复制链表
* <p>
* 给定一种特殊的链表,random是链表中额外的指针,可能指向链表中的任意一个节点,也可能指向null
*/
public class CopyLinkedNode {

/**
* hash表实现
*
* @param head 头节点
* @return 复制链表
*/
public Node copyLinkedNode(Node head) {
if (head == null) {
return null;
}
HashMap<Node, Node> nodeMap = new HashMap<>();
Node cur = head;
while (cur != null) {
nodeMap.put(cur, new Node(cur.value));
cur = cur.next;
}
cur = head;
while (cur != null) {
nodeMap.get(cur).next = nodeMap.get(cur.next);
nodeMap.get(cur).random = nodeMap.get(cur.random);
cur = cur.next;
}
return nodeMap.get(head);
}

/**
* 把每个节点的复制节点挂在该节点后面,每个节点的复制节点的random指针指向的位置就在原位置的next位置,random指向完成后,分离链表
*
* @param head 头节点
* @return 复制链表
*/
// public Node copyLinkedNode(Node head) {}

/**
* 链表结构
*/
public static class Node {

public int value;

public Node next;

public Node random;

public Node(int value) {
this.value = value;
}

}

}

/* 如有意见或建议,欢迎评论区留言;如发现代码有误,欢迎批评指正 */
原文地址:https://www.cnblogs.com/laydown/p/12839571.html