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 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 * 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) { 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 != NULL) 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; } };
python版
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 class Solution : def copyRandomList (self, head) : cur=head while (cur): node=RandomListNode(cur.label) node.next=cur.next cur.next=node cur=node.next cur=head while (cur): if (cur.random!=None ): cur.next.random=cur.random.next cur=cur.next.next dummy=RandomListNode(0 ) new_cur=dummy cur=head while (cur): new_cur.next=cur.next new_cur=cur.next cur.next=cur.next.next cur=cur.next return dummy.next