複製帶隨機指針的鏈表(LeetCode中級篇138題)

給定一個鏈表,每個節點包含一個額外增加的隨機指針,該指針可以指向鏈表中的任何節點或空節點。

要求返回這個鏈表的深度拷貝。

/**
 * Definition for singly-linked list with a random pointer.
 * struct RandomListNode {
 *     int label;
 *     struct RandomListNode *next;
 *     struct RandomListNode *random;
 * };
 */
typedef struct RandomListNode RLNote;
struct RandomListNode *copyRandomList(struct RandomListNode *head) {
    //第一步,先複製鏈表中的所有結點
    RLNote *cur = head;
    RLNote *next;
    while(cur)
    {
        next = cur->next;
        RLNote *copy =(RLNote *)malloc(sizeof(RLNote));
        copy->label = cur->label;
        cur->next = copy;
        copy->next = next;
        cur = next;
    }
    //第二步,將random連接起來
    cur = head;
    while(cur)
    {
        RLNote* copy = cur->next;
        if(cur->random)
            copy->random = cur->random->next;
        else
            copy->random = NULL;
        cur = copy->next;
    }
    //第三步,將copy提取出來
    RLNote* copyhead,* tail ;
    copyhead = tail = (RLNote*)malloc(sizeof(RLNote));
    cur = head;
    while(cur)
    {
        RLNote* copy = cur->next;
        RLNote* next = copy->next;
        
        tail -> next = copy;
        tail = copy;
        //鏈接原鏈表的所有next
        cur -> next = next;  
        //循環下一個時將cur指向next
        cur = next; 
    }
    RLNote* newnode = copyhead->next;
    free(copyhead);
    return newnode;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章