Copy List with Random Pointer

来源:互联网 发布:伊修巴尔歼灭战 知乎 编辑:程序博客网 时间:2024/06/10 16:22

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.

按照单链表的顺序从头到尾遍历链表,同时创建新的节点,记录新节点与旧节点的对应关系,最后再一次从头到尾遍历节点处理rand节点的值。

/** * 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;        RandomListNode *res = new RandomListNode(head->label);        RandomListNode *node = res;        RandomListNode *cur = head->next;        map<RandomListNode*, RandomListNode*> m;        m[head] = res;        while (cur) {            RandomListNode *tmp = new RandomListNode(cur->label);            node->next = tmp;            m[cur] = tmp;            node = node->next;            cur = cur->next;        }        node = res;        cur = head;        while (node) {            node->random = m[cur->random];            node = node->next;            cur = cur->next;        }        return res;    }};
0 0
原创粉丝点击