36:Copy List with Random Pointer

来源:互联网 发布:android 全景拼接算法 编辑:程序博客网 时间:2024/06/11 07:35

本题解法代码的思想及编写参考了网址https://github.com/soulmachine/leetcode#leetcode题解

题目: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.

解题代码如下:

class Solution {public:        RandomListNode* copyRandomList(RandomListNode* head) {                for (RandomListNode* cur = head; cur != nullptr;) {                        RandomListNode* node = new RandomListNode(cur -> label);                                                node -> next = cur -> next;                        cur -> next = node;                        cur = node -> next;                }                for (RandomListNode* cur = head; cur != nullptr; ) {                        if (cur -> random != nullptr)                                cur -> next -> random = cur -> random -> next;                        cur = cur -> next -> next;                }                // 分拆成两个单链表                RandomListNode dummy{-1};                for (RandomListNode *cur = head, *new_cur = &dummy; cur != nullptr; ) {                        new_cur -> next = cur -> next;                        new_cur = new_cur -> next;                        cur -> next = cur -> next -> next;                        cur = cur -> next;                }                return dummy.next;        }};
0 0
原创粉丝点击