复制带随机指针的链表

题目

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

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

代码

/**
 * Definition for singly-linked list with a random pointer.
 * struct RandomListNode {
 *     int label;
 *     RandomListNode *next, *random;
 *     RandomListNode(int x) : label(x), next(NULL), random(NULL) {}
 * };
 */
class Solution {
public:
    RandomListNode *copyRandomList(RandomListNode *head) {
        if (head == NULL)
            return head;
        RandomListNode* cur = head;
        //第一遍扫描:对每个结点进行复制,把复制出来的新结点插在原结点之后 
        while (cur != NULL) {
            RandomListNode* newNode = new RandomListNode(cur->label);
            newNode->next = cur->next;
            cur->next = newNode;
            cur = newNode->next;
        }
        cur = head;
        //第二遍扫描:根据原结点的random,给新结点的random赋值  
        while (cur != NULL) {
            if (cur->random != NULL) {
                cur->next->random = cur->random->next;
            }
            cur = cur->next->next;
        }
        cur = head->next;
        RandomListNode* newHead = cur;
        RandomListNode* old = head;
        //第三遍扫描:把新结点从原链表中拆分出来  
        while (old != NULL) {
            old->next = old->next->next;
            if (old->next != NULL) {
                cur->next = old->next->next;
            }
            cur = cur->next;
            old = old->next;
        }
        return newHead;
    }
};

猜你喜欢

转载自blog.csdn.net/m0_37947204/article/details/80593193