LeetCode | Copy List with Random Pointer

题目:

A linked list is given such that each node contains an additional random pointer which could point to any node in the list or null.

Return a deep copy of the list.

思路:

普通的链表复制就是遍历一次就能够得到结果,因此遍历一次我们可以将next这个链表复制完成。而random在第一次遍历的时候我们可以暂时指向原始结点的位置。为了在第二次遍历是确定random的位置,我们可以存储复制结点与原始结点的关系。这个可以由map来完成。

代码:

/**
 * 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) {
        map<RandomListNode*, RandomListNode*> relation;
        
        RandomListNode* copiedHead= NULL;
        RandomListNode* copiedPtr=NULL;
        RandomListNode* ptr = head;
        
        while(ptr!=NULL)
        {
            RandomListNode* new_node = new RandomListNode(ptr->label);
            relation.insert(pair<RandomListNode*, RandomListNode*>(ptr, new_node));
            if(copiedHead==NULL)
            {
                copiedHead = new_node;
                copiedPtr = new_node;
            }
            else
            {
                copiedPtr->next = new_node;
                copiedPtr=copiedPtr->next;
            }
            copiedPtr->random = ptr->random;
            ptr=ptr->next;
        }
        
        ptr=head;
        copiedPtr = copiedHead;
        while(ptr!=NULL)
        {
            if(ptr->random!=NULL)
            {
                copiedPtr->random = relation[ptr->random];
            }
            copiedPtr=copiedPtr->next;
            ptr=ptr->next;
        }
        return copiedHead;
    }
};
    原文作者:Allanxl
    原文地址: https://blog.csdn.net/lanxu_yy/article/details/17801575
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞