Return a deep copy of the list.
题目中给定了一个链表,链表中的节点类有三个成员,label,next,random,其中label和next和普通链表中的一样,多了一个random,random指针指向链表中的任意一个元素或者指向空,要求我们复制这个链表。这道题目和 Clone Graph很类似。我们都需要借助一个哈希表来存储新建节点和老节点之间的对应关系,然后在对链表扫描一遍,如果当前节点的random指针不为空,那么这个节点对应的copy节点的random要指向相应的节点,这些对应的关系都是在哈希表找到的。代码如下:
/** * 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) { HashMap<RandomListNode, RandomListNode> hm = new HashMap<RandomListNode, RandomListNode>(); if(head == null) return head; RandomListNode copy = new RandomListNode(head.label); hm.put(head, copy); RandomListNode node = copy; RandomListNode helper = head; while(head.next != null) { copy.next = new RandomListNode(head.next.label); hm.put(head.next, copy.next); head = head.next; copy = copy.next; } while(helper != null) { if(helper.random != null) { hm.get(helper).random = hm.get(helper.random); } helper = helper.next; } return node; } }