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:
  5. RandomListNode *copyRandomList(RandomListNode *head) {
  6. for (RandomListNode* cur = head; cur != nullptr; ) {
  7. RandomListNode* node = new RandomListNode(cur->label);
  8. node->next = cur->next;
  9. cur->next = node;
  10. cur = node->next;
  11. }
  12. for (RandomListNode* cur = head; cur != nullptr; ) {
  13. if (cur->random != NULL)
  14. cur->next->random = cur->random->next;
  15. cur = cur->next->next;
  16. }
  17. // 分拆两个单链表
  18. RandomListNode dummy(-1);
  19. for (RandomListNode* cur = head, *new_cur = &dummy;
  20. cur != nullptr; ) {
  21. new_cur->next = cur->next;
  22. new_cur = new_cur->next;
  23. cur->next = cur->next->next;
  24. cur = cur->next;
  25. }
  26. return dummy.next;
  27. }
  28. };

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