标签:color which lin point ext code 哈希表 map his
A linked list is given such that each node contains an additional random pointer which could point to any node in the list or null.
Return a deep copy of the list.
想了好久才明白deep copy的含义在于新链表的next 和 random指针要指向新链表中的node,而单纯用“=”的话就会指向旧链表。
所以要用哈希表来将新旧node进行对应。
/** * Definition for singly-linked list with a random pointer. * class RandomListNode { * int label; * RandomListNode next, random; * RandomListNode(int x) { this.label = x; } * }; */ public class Solution { public RandomListNode copyRandomList(RandomListNode head) { RandomListNode node = head; if(node == null) return null; Map<RandomListNode,RandomListNode> map = new HashMap<>(); while(node != null) { map.put(node, new RandomListNode(node.label)); 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); } }
138. Copy List with Random Pointer
标签:color which lin point ext code 哈希表 map his
原文地址:https://www.cnblogs.com/jamieliu/p/10349219.html