LeetCode | 138. 随机链表的复制

LeetCode | 138. 随机链表的复制

OJ链接
LeetCode | 138. 随机链表的复制_第1张图片

思路:

  • 题目要求我们拷贝一个带next指针与random随机访问指针的链表。

  • 如果只拷贝一个只带next的指针,直接遍历目标链表依次拷贝每个节点的信息就可以了~~

    • 拷贝节点插入到原节点的后面
    • 处理copy节点的random
    • copy节点下来的尾插
struct Node* copyRandomList(struct Node* head) {
	struct Node* cur = head;
    //拷贝节点插入到原节点的后面
    while(cur)
    {
	    struct Node* copy = (struct Node*)malloc(sizeof(struct Node));
        copy->val = cur->val;

        copy->next = cur->next;
        cur->next = copy;

        //cur = copy->next;
        cur = cur->next->next;

    }
    //处理copy节点的random
    cur = head;
    while(cur)
    {
        struct Node* copy = cur->next;
        if(cur->random == NULL)
        {
            copy->random = NULL;
        }
        else
        {
            copy->random = cur->random->next;
        }
        cur = cur->next->next;
    }
    //copy节点下来的尾插
    struct Node* newhead = NULL,*tail = NULL;
    cur = head;
    while(cur)
    {
        struct Node* copy = cur->next;
        struct Node* next = copy->next;
        if(tail == NULL)
        {
            newhead = tail = copy;
        }
        else
        {
            tail->next = copy;
            tail = tail->next;
        }
        copy->next = next;
        cur = next;
    }
    return newhead;
}

你可能感兴趣的:(LeetCode,leetcode,链表,算法)