程序员成长之旅——复制带随机指针的链表

程序员成长之旅——复制带随机指针的链表

题目简介

给定一个链表,每个节点包含一个额外增加的随机指针,该指针可以指向链表中的任何节点或空节点。

要求返回这个链表的深拷贝。

LeetCode

/*
// Definition for a Node.
class Node {
public:
    int val;
    Node* next;
    Node* random;

    Node() {}

    Node(int _val, Node* _next, Node* _random) {
        val = _val;
        next = _next;
        random = _random;
    }
};
*/
Node* BuyNode(int val)
{
    Node* newnode = (Node*)malloc(sizeof(Node));
    if(newnode == NULL)
    {
        return NULL;
    }
    newnode->val = val;
    newnode->next =NULL;
    newnode->random = NULL;
    return newnode;
}
class Solution {
public:
    Node* copyRandomList(Node* head) {
        //拷贝插入
        Node* cur = head;
        while(cur)
        {
            //记录cur的下一个结点
            Node* next = cur->next;
            //拷贝相同结点
            Node* cpnode = BuyNode(cur->val);
            //插入新结点
            cur->next = cpnode;
            cpnode->next = next;
            //迭代走起来
            cur = next;
        }
        
        //置random
        cur = head;
        while(cur)
        {
            Node* next = cur->next->next;
            Node* cpnode = cur->next;
            
            if(cur->random != NULL)
            cpnode->random = cur->random->next;
            
            if(cur->random == NULL)
            cpnode->random = NULL;
                
            cur = next;
        }
        
        //拆解-链接
        Node* pHead = BuyNode(0);
        Node* tail = pHead;
        cur = head;
        while(cur)
        {
            Node* cpnode = cur->next;
            cur->next = cpnode->next;
            cur = cpnode->next;
            cpnode->next = NULL;
            
            tail->next = cpnode;
            tail = cpnode;
            
        }
        Node* phead = pHead->next;
        free(pHead);
        return phead;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

从零出发——

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

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

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

打赏作者

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

抵扣说明:

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

余额充值