138. 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.

解题思路:

1. 每个节点除了next指针还有random指针,所以我们可以用一个map将原节点和新节点形成一个1对1映射,然后在遍历节点找到其对应的random指向的节点。

2. 直接复制每个节点并连接到节点后面:

  temp->next = p->next;

  p->next = temp;

  p = temp->next;

 然后复制random指针:

  temp = p->next;

  if(p->random)

    temp->random = p->random->next;

 然后断开成两个链表:

  temp = p->nextl

  p->next = temp->next;

  if(p->next)

    temp->next = p->next;

跪服大神:水中的鱼

  

代码:

解法一:用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) {
        if(!head)
            return head;
        unordered_map<RandomListNode*, RandomListNode*> nodeMap;
        RandomListNode *p = head;
        RandomListNode *pre = p;
        while(p){
            RandomListNode *temp = new RandomListNode(p->label);
            nodeMap[p] = temp;
            if(p != head){
                pre->next = temp;
            }
            pre = temp;
            p = p->next;
        }
        p = head;
        
        while(p){
            RandomListNode *node = nodeMap[p];
            if(p->random){
                RandomListNode *rNode = nodeMap[p->random];
                node->random = rNode;
            }
            p = p->next;
        }
        return nodeMap[head];
    }
};

解法二:在链表上进行操作。

/**
 * 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)
            return head;
        RandomListNode *p = head;
        //copy nodes and insert them
        while(p){
            RandomListNode *temp = new RandomListNode(p->label);
            temp->next = p->next;
            p->next = temp;
            p = temp->next;
        }
        //copy random pointer
        p = head;
        while(p){
            RandomListNode *temp = p->next;
            if(p->random){
                temp->random = p->random->next;
            }
            p = temp->next;
        }
        
        RandomListNode *ret = head->next;
        p = head;
        RandomListNode *temp = ret;
        while(p){
            p->next = temp->next;
            if(temp->next){
                temp->next = temp->next->next;
            }
            p = p->next;
            temp = temp->next;
        }
        return ret;
        
    }
};

猜你喜欢

转载自www.cnblogs.com/yaoyudadudu/p/9124335.html