學渣帶你刷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;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章