码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode138

时间:2018-10-21 21:48:34      阅读:116      评论:0      收藏:0      [点我收藏+]

标签:leetcode   color   str   nbsp   维护   style   span   turn   关系   

/**
 * 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 NULL;
        unordered_map<RandomListNode*, RandomListNode*> mp;
        // 创建一个新的链表头
        RandomListNode *new_head = new RandomListNode(head->label);
        // node1负责指向原链表,node2负责指向新链表
        RandomListNode *node1 = head, *node2 = new_head;
        /**
         * 按照原链表的结构不断创建新的节点,并维护好next指针,将node1与node2的对应关系保存到hash_map中,
         * 以备后面维护random指针的时候,可以通过node1找到对应的node2。
         */
        while (node1->next != NULL) {
            mp[node1] = node2;
            node1 = node1->next;
            node2->next = new RandomListNode(node1->label);
            node2 = node2->next;
        }
        // 将两个链表的尾巴的对应关系也保存好
        mp[node1] = node2;
        
        // 继续从头开始处理random指针
        node1 = head;
        node2 = new_head;
        while (node1->next != NULL) {
            node2->random = mp[node1->random];
            node1 = node1->next;
            node2 = node2->next;
        }
        // 把尾巴的random指针也处理好
        node2->random = mp[node1->random];
        return new_head;
    }
};

 

leetcode138

标签:leetcode   color   str   nbsp   维护   style   span   turn   关系   

原文地址:https://www.cnblogs.com/asenyang/p/9826727.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!