【数据结构--链表】复制带随机指针的链表

题目描述: 

 

 实现思路:

 

 代码实现:

/**
 * Definition for a Node.
 * struct Node {
 *     int val;
 *     struct Node *next;
 *     struct Node *random;
 * };
 */
struct Node* Buy_Capacity(int x)//每次插入(头插尾插)都要创建新节点,可以将此过程封装
{
	struct Node* newnode = (struct Node*)malloc(sizeof(struct Node));
	if (newnode == NULL)//创建新节点失败
	{
		perror("malloc fail!");
		return 0;
	}
	newnode->val = x;
	newnode->next = newnode->random = NULL;
	return newnode;
}


struct Node* copyRandomList(struct Node* head) {
	//在每个节点后面拷贝插入一个新节点
    struct Node*cur=head;
    while(cur)
    {
        struct Node* newnode=Buy_Capacity(cur->val);
        struct Node* next=cur->next;
        cur->next=newnode;
        newnode->next=next;
        cur=cur->next->next;
    }
    //再建立新创建的节点之间random的关系
    cur=head;
    while(cur)
    {
        if(cur->random==NULL)
        {
            cur->next->random=NULL;
        }
        else
        {
            cur->next->random=cur->random->next;
        }
        cur=cur->next->next;
    }
    //最后断开原节点和新节点,并返回新节点的头
    cur=head;
    struct Node*newhead=NULL,*tail=NULL;//要记得初始化,否则会造成非法访问的问题
    while(cur)
    {
        struct Node* list=cur->next->next;
        if(newhead==NULL)
        {
            newhead=tail=cur->next;
            cur->next=list;
        }
        else
        {
            tail->next=cur->next;
            cur->next=list;
            tail=tail->next;
        }
        cur=cur->next;
    }
    return newhead;
}

评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

伱恏呀呀呀呀

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值