复制带随机指针的链表(leetcode中级篇一百三十八题)

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

ps:要求返回这个链表的深度拷贝

在这里插入图片描述

/**
 * Definition for singly-linked list with a random pointer.
 * struct RandomListNode {
 *     int label;
 *     struct RandomListNode *next;
 *     struct RandomListNode *random;
 * };
 */
typedef struct RandomListNode RLNode;

struct RandomListNode *copyRandomList(struct RandomListNode *head) {
    RLNode* cur = head;   
    while(cur)//复制链表
    {
        RLNode* next = cur -> next;
        RLNode* copy = (RLNode*)malloc(sizeof(RLNode));
        copy -> label = cur -> label;
        cur -> next = copy;
        copy -> next = next;
        
        cur = next;
    }    
    cur = head;
    while(cur)//调整指针
    {
        RLNode* copy = cur -> next;
        if(cur -> random)
        {
            copy -> random = cur -> random -> next;
        }
        else
        {
            copy -> random = NULL;
        }
        
        cur = copy -> next;
    }
    RLNode* tail, *copyhead;
    tail = copyhead = (RLNode*)malloc(sizeof(RLNode));
    cur = head;
    while(cur)//进行拆解
    {
        RLNode* copy = cur -> next;
        RLNode* next = copy -> next;
        
        tail -> next = copy;
        tail = copy;
        
        cur -> next = next;        
        cur = next;
    }
    RLNode* newnode = copyhead -> next;
    free(copyhead);
    
    return newnode;
}

猜你喜欢

转载自blog.csdn.net/lucky52529/article/details/84996159