[Lintcode] 105. Copy List with Random Pointer

来源:互联网 发布:悍将传世源码 编辑:程序博客网 时间:2024/06/05 04:57

给出一个链表,每个节点包含一个额外增加的随机指针可以指向链表中的任何节点或空的节点。

返回一个深拷贝的链表。

public class Solution {      public RandomListNode copyRandomList(RandomListNode head) {          if (head == null) {              return null;          }                    HashMap<RandomListNode, RandomListNode> map = new HashMap<RandomListNode, RandomListNode>();          RandomListNode dummy = new RandomListNode(0);          RandomListNode pre = dummy, newNode;          while (head != null) {              if (map.containsKey(head)) {                  newNode = map.get(head);              } else {                  newNode = new RandomListNode(head.label);                  map.put(head, newNode);              }              pre.next = newNode;                            if (head.random != null) {                  if (map.containsKey(head.random)) {                      newNode.random = map.get(head.random);                  } else {                      newNode.random = new RandomListNode(head.random.label);                      map.put(head.random, newNode.random);                  }              }                            pre = newNode;              head = head.next;          }                    return dummy.next;      }  }