学渣带你刷Leetcode138. 复制带随机指针的链表

题目描述

白话题目:
 

算法:

 

详细解释关注 B站  【C语言全代码】学渣带你刷Leetcode 不走丢 https://www.bilibili.com/video/BV1C7411y7gB

C语言完全代码

/**
 * Definition for a Node.
 * struct Node {
 *     int val;
 *     struct TreeNode *next;
 *     struct TreeNode *random;
 * };
 */

struct Node* copyRandomList(struct Node* head) {
	if(!head) return NULL;

    /*使用next将整个链表构建起来*/
    
    struct Node *head1 = (struct Node *)malloc(sizeof(struct Node));
    head1->val = head->val;
    head1->next = NULL;
    head1->random = NULL;

    struct Node* h = head, * h1 = head1;

    while(h->next){
        h = h->next;
        struct Node * temp = (struct Node *)malloc(sizeof(struct Node));
        temp->val = h->val;
        temp->next = NULL;
        temp->random = NULL;
        
        h1->next = temp;
        h1 = h1->next;
    }
    /*处理那个随机指针*/

    h = head; h1 = head1; 
    while(h){
        if(!h) break;

        int index=0;
        struct Node * cur=head, * cur1=head1;

        if(h->random){
            while(cur && cur!=h->random){
                index++;
                cur = cur->next;
            }
            while(index){
                index--;
                cur1 = cur1->next;
            }
            h1->random = cur1;
        }
        else h1->random = NULL;
        
        h = h->next;
        h1 = h1->next;
    }
    return head1;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值