1. 复杂链表的复制

  • 请实现 copyRandomList 函数,复制一个复杂链表。在复杂链表中,每个节点除了有一个 next 指针指向下一个节点,还有一个 random 指针指向链表中的任意节点或者 null。 ``` 示例 1:

输入:head = [[7,null],[13,0],[11,4],[10,2],[1,0]] 输出:[[7,null],[13,0],[11,4],[10,2],[1,0]] 示例 2:

输入:head = [[1,1],[2,1]] 输出:[[1,1],[2,1]] 示例 3:

输入:head = [[3,null],[3,0],[3,null]] 输出:[[3,null],[3,0],[3,null]] 示例 4:

输入:head = [] 输出:[] 解释:给定的链表为空(空指针),因此返回 null。

提示:

-10000 <= Node.val <= 10000 Node.random 为空(null)或指向链表中的节点。 节点数目不超过 1000 。

  1. <a name="pzxVJ"></a>
  2. ### 思路:
  3. - 使用两个辅助指针
  4. - 一个指向被赋值链表,进行扫描
  5. - 一个指向新建的copy的表
  6. - 第一次遍历整个原链表,进行新链表中next指针的构建
  7. - 第二次遍历,进行random结点的构建
  8. <a name="Ohh2t"></a>
  9. #### 重点:
  10. - 由于每个结点没有唯一标识,所以不能通过遍历结点的某一属性去查找对应链表,进行random的连接
  11. - 那么这里就可以使用map的key|value结构,在构建next结点的时候,将原链表与新链表的每一个结点对应起来,这样的话就能找原链表的random结点的时候,就直接使用map.get(cur.random),此时原链表中某个结点的random结点对应的value,对应的就是新链表中对应结点的random结点。
  12. ```java
  13. class Solution {
  14. public Node copyRandomList(Node head) {
  15. if(head==null) return null;
  16. Map<Node,Node> map = new HashMap<>();
  17. Node res = new Node(head.val);
  18. Node temp = res;
  19. Node cur = head;
  20. while(cur.next!=null){
  21. temp.next = new Node(cur.next.val);
  22. map.put(cur,temp);
  23. temp = temp.next;
  24. cur = cur.next;
  25. }
  26. map.put(cur,temp);
  27. cur = head;
  28. temp = res;
  29. while(cur!=null){
  30. if(cur.random!=null){
  31. // temp.random = getByVal(res,cur.random.val);
  32. temp.random = map.get(cur.random);
  33. }else{
  34. temp.random = null;
  35. }
  36. temp = temp.next;
  37. cur = cur.next;
  38. }
  39. return res;
  40. }
  41. // public Node getByVal(Node head,int target){
  42. // Node temp = head;
  43. // while(temp!=null){
  44. // if(temp.val==target){
  45. // return temp;
  46. // }
  47. // temp = temp.next;
  48. // }
  49. // return null;
  50. // }
  51. }