Copy List with Random Pointer

描述

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.

分析

代码

  1. // Copy List with Random Pointer
  2. // 两遍扫描,时间复杂度O(n),空间复杂度O(1)
  3. class Solution {
  4. public RandomListNode copyRandomList(RandomListNode head) {
  5. for (RandomListNode cur = head; cur != null; ) {
  6. RandomListNode node = new RandomListNode(cur.label);
  7. node.next = cur.next;
  8. cur.next = node;
  9. cur = node.next;
  10. }
  11. for (RandomListNode cur = head; cur != null; ) {
  12. if (cur.random != null)
  13. cur.next.random = cur.random.next;
  14. cur = cur.next.next;
  15. }
  16. // 分拆两个单链表
  17. RandomListNode dummy = new RandomListNode(-1);
  18. for (RandomListNode cur = head, new_cur = dummy;
  19. cur != null; ) {
  20. new_cur.next = cur.next;
  21. new_cur = new_cur.next;
  22. cur.next = cur.next.next;
  23. cur = cur.next;
  24. }
  25. return dummy.next;
  26. }
  27. };

原文: https://soulmachine.gitbooks.io/algorithm-essentials/content/java/linear-list/linked-list/copy-list-with-random-pointer.html