创新工场笔试题Copy List with Random Pointer

假设有如下一个链表:

1
2
3
4
5
6
struct Node
{
     int value ;
     struct Node *next ;
     struct Node *random ;
}
其中,random指向该链表的任意一个节点或者NULL,请编程实现该链表的深拷贝。
1
Node *deepCopy (Node *head)
解析:把新节点插入到相应的旧节点后面:


分两步

    1、构建新节点random指针:new1->random = old1->random->next, new2-random = NULL, new3-random = NULL, new4->random = old4->random->next

    2、恢复原始链表以及构建新链表:例如old1->next = old1->next->next, new1->next = new1->next->next

    该算法时间复杂度O(N),空间复杂度O(1)

代码:

Node *deepCopy (Node *head)
{
    Node* now = head;
    Node* next = head->next;
    while( now != NULL )
    {
         Node * copy = new Node;
         copy->value = now->value;
         copy->next  = now->next;
         now ->next  = copy;
         now         = next;
         next        = next->next;
    }
    now = head;
    while( now != NULL )
    {
         now->next->random = now->random->next;
         now = now->next->next;
    }
    Node* head2 = head->next;
    Node* newHead = head->next;
    while( head2->next != NULL )
    {
        head->next = head2->next;
        head2->next = head2->next->next;
        head = head->next;
        head2 = head2->next;
    }
     
    return newHead;
}





 



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值