题目

输入一个复杂链表(每个节点中有节点值,以及两个指针,一个指向下一个节点,另一个特殊指针指向任意一个节点),返回结果为复制后复杂链表的head。(注意,输出结果中请不要返回参数中的节点引用,否则判题程序会直接返回空)

分析

  • 用一个 hashmap 建立新旧链表节点的对应的结点关系
  • 迭代旧链表,从而在 hashmap 中更新新链表的 next 与 random 两个字段

    代码一

    ```java public class RandomListNode { int label; RandomListNode next = null; RandomListNode random = null;

    RandomListNode(int label) {

    1. this.label = label;

    }

}

public RandomListNode Clone(RandomListNode pHead) { RandomListNode p = pHead; RandomListNode pp = pHead; if(pHead == null)return pHead; HashMap map = new HashMap(); //制造map while(p!=null) { map.put(p, new RandomListNode(p.label)); p=p.next; }

  1. //把map里的value关联起来
  2. while(pp!=null)
  3. {
  4. if(pp.next!=null)
  5. {
  6. map.get(pp).next = map.get(pp.next);
  7. }else
  8. {
  9. map.get(pp).next = null;
  10. }
  11. map.get(pp).random = map.get(pp.random);
  12. pp=pp.next;
  13. }
  14. return map.get(pHead);
  15. }
  1. <a name="Ix81X"></a>
  2. #### 代码二
  3. <a name="AVzAl"></a>
  4. #### 分析
  5. ![](https://cdn.nlark.com/yuque/0/2020/png/1206300/1586619005056-96eced2a-52f0-4adc-b095-e394ff1cd600.png#align=left&display=inline&height=540&originHeight=540&originWidth=461&size=0&status=done&style=none&width=461)
  6. ```java
  7. public class Solution {
  8. public RandomListNode Clone(RandomListNode pHead) {
  9. if(pHead == null) {
  10. return null;
  11. }
  12. RandomListNode currentNode = pHead;
  13. //1、复制每个结点,如复制结点A得到A1,将结点A1插到结点A后面;
  14. while(currentNode != null){
  15. RandomListNode cloneNode = new RandomListNode(currentNode.label);
  16. RandomListNode nextNode = currentNode.next;
  17. currentNode.next = cloneNode;
  18. cloneNode.next = nextNode;
  19. currentNode = nextNode;
  20. }
  21. currentNode = pHead;
  22. //2、重新遍历链表,复制老结点的随机指针给新结点,如A1.random = A.random.next;
  23. while(currentNode != null) {
  24. currentNode.next.random = currentNode.random==null?null:currentNode.random.next;
  25. currentNode = currentNode.next.next;
  26. }
  27. //3、拆分链表,将链表拆分为原链表和复制后的链表
  28. currentNode = pHead;
  29. RandomListNode pCloneHead = pHead.next;
  30. while(currentNode != null) {
  31. RandomListNode cloneNode = currentNode.next;
  32. currentNode.next = cloneNode.next;
  33. cloneNode.next = cloneNode.next==null?null:cloneNode.next.next;
  34. currentNode = currentNode.next;
  35. }
  36. return pCloneHead;
  37. }
  38. }