Copy List with Random Pointer

本文介绍了一种复杂链表的深拷贝方法,这种链表除了常规的next指针外还包含指向任意节点的随机指针。通过在每个节点后插入复制节点并调整连接方式,实现了一个高效的解决方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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.

<span style="font-size:18px;">/**
 * Definition for singly-linked list with a random pointer.
 * struct RandomListNode {
 *     int label;
 *     RandomListNode *next, *random;
 *     RandomListNode(int x) : label(x), next(NULL), random(NULL) {}
 * };
 */
class Solution {
public:
    RandomListNode *copyRandomList(RandomListNode *head) {
        RandomListNode *copyhead,*copy_ptr,*tmp,*p=head;
        if(!head)
            return NULL;
        while(p)//第一步往列表每一个元素后面插入一个元素,该元素的值与前一个相同
        {
            copy_ptr=new RandomListNode(p->label);
            copy_ptr->next=p->next;
            p->next=copy_ptr;
            if(copy_ptr->next)
                p=copy_ptr->next;
            else
                break;
        }
        p=head;
        copy_ptr=head->next;
        while(p)//第二步把random指针正确置位
        {
            if(p->random==NULL)
                copy_ptr->random=NULL;
            else
                copy_ptr->random=p->random->next;
            if(p->next)
                p=p->next->next;
            if(copy_ptr->next)
                copy_ptr=copy_ptr->next->next;
        }
        copyhead=head->next;
        copy_ptr=head->next;
        p=head;
	    while(copy_ptr->next)//拆分两个链表
	    {
	        
	        p->next=copy_ptr->next;
	        p=copy_ptr;
	        if(copy_ptr->next!=NULL)
	             copy_ptr=copy_ptr->next;
		  
	    }
	    p->next=NULL;
    return copyhead;
    }
};</span>


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值