首页 > 编程语言 > 详细

力扣算法——138CopyListWithRandomPointer

时间:2019-11-06 23:30:32      阅读:94      评论:0      收藏:0      [点我收藏+]

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.

 

Example 1:

技术分享图片

Input:
{"$id":"1","next":{"$id":"2","next":null,"random":{"$ref":"2"},"val":2},"random":{"$ref":"2"},"val":1}

Explanation:
Node 1‘s value is 1, both of its next and random pointer points to Node 2.
Node 2‘s value is 2, its next pointer points to null and its random pointer points to itself.

 

Note:

  1. You must return the copy of the given head as a reference to the cloned list.

Solution:

   方法一:
     使用哈希表,将链表值与节点地址对应,先复制一条主链,并用哈希表记录新链的节点值与节点地址的对应

     然后遍历原链表,通过原链表随机指针的值,和哈希表,来找到新链所对应的随机指针

    缺点:需要额外的空间,并且节点值不能相同,否则哈希表失效

  方法二:

    将新链直接复制在主链后面,那么当复制随机指针时,新链的随机指针值就在旧链的随机值后面

    然后将新链从主链中脱离出来

  

 1 class Solution {
 2 public:
 3     RandomListNode *copyRandomList(RandomListNode *head) {
 4         RandomListNode* p = head;
 5         while (p != nullptr)
 6         {
 7             RandomListNode* q = new RandomListNode(p->label);
 8             q->next = p->next;
 9             p->next = q;
10             p = p->next->next;
11         }
12         p = head;
13         while (p != nullptr)
14         {
15             if (p->random != nullptr)
16                 p->next->random = p->random->next;
17             p = p->next->next;
18         }
19         p = head;
20         RandomListNode *resHead = new RandomListNode(-1), *q;
21         q = resHead;
22         while (p != nullptr)
23         {
24             q->next = p->next;
25             q = q->next;
26             p->next = p->next->next;
27             p = p->next;
28         }
29         return resHead->next;
30     }
31 };

 

  

力扣算法——138CopyListWithRandomPointer

原文:https://www.cnblogs.com/zzw1024/p/11809316.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!