/* // 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; } }; */ public solution{ //HashMap中旧结点存储为键,新结点存储为值。 HashMap<Node,Node> visitedHash=new HashMap<Node,Node>(); public Node copeRandomList(Node head){ if(head==null) returnnull; //如果存在当前结点,直接返回它的复制。 if(this.visitedHash.containsKey(head)) returnthis.visitedHash.get(head); //若不存在,则创建一个新结点。 Node node=new Node(head.val,null,null); //将其放入HashMap this.visitedHash.put(head,node); //循环下一结点 node.next=this.copeRandomList(head.next); node.random=this.copeRandomList(head.random); return node; } }
publicclasssolution{ // Visited dictionary to hold old node reference as "key" and new node reference as the "value" HashMap<Node, Node> visited = new HashMap<Node, Node>(); //获取复制结点 public Node getClonedNode(Node node){ // If the node exists then if (node != null) { // Check if the node is in the visited dictionary if (this.visited.containsKey(node)) { // If its in the visited dictionary then return the new node reference from the dictionary returnthis.visited.get(node); } else { // Otherwise create a new node, add to the dictionary and return it this.visited.put(node, new Node(node.val, null, null)); returnthis.visited.get(node); } } returnnull; } //复制带有random指针的链表。 public Node copyRandomList(Node head){
if (head == null) { returnnull; }
Node oldNode = head;
// Creating the new head node. Node newNode = new Node(oldNode.val); this.visited.put(oldNode, newNode);
// Iterate on the linked list until all nodes are cloned. while (oldNode != null) { // Get the clones of the nodes referenced by random and next pointers. newNode.random = this.getClonedNode(oldNode.random); newNode.next = this.getClonedNode(oldNode.next);
// Move one step ahead in the linked list. oldNode = oldNode.next; newNode = newNode.next; } returnthis.visited.get(head); } }