[LeetCode] 138. Copy List with Random Pointer

来源:互联网 发布:苹果手机九格切图软件 编辑:程序博客网 时间:2024/05/14 02:55

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.


问题描述:

给定一个单链表,在传统的单链表的基础之上,每个节点还增加了一个random指针,指向链表中的任意一个节点或者null。

请深度复制整个链表。

    RandomListNode *copyRandomList(RandomListNode *head) {        if (head == nullptr) return nullptr;        RandomListNode *newhead = new RandomListNode(head->label);        RandomListNode *pold = head, *pnew = newhead;        unordered_map<RandomListNode *, RandomListNode *> map;        map[pold] = pnew;// 遍历链表,为新旧链表对应位置上的节点建立一个映射关系。        while (pold->next != nullptr) {            pnew->next = new RandomListNode(pold->next->label);            pold = pold->next;            pnew = pnew->next;            map[pold] = pnew;        }        // 由于新链表所有的节点都已经存在。故我们可以用映射关系为每个新节点设置其random指针。        pold = head, pnew = newhead;        while (pold != nullptr) {            assert(!map.count(pold->random));            pnew->random = map[pold->random];            pold = pold->next;            pnew = pnew->next;        }                return newhead;    }


原创粉丝点击