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.
C++
/** * 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) { RandomListNode *copy,*p; if (!head) return NULL; for(p=head;p;p=p->next){ copy = new RandomListNode(p->label); copy->next = p->next; p = p->next = copy; } for(p=head;p;p=copy->next){ copy = p->next; copy->random = (p->random ? p->random->next:NULL); } for(p=head,head=copy=p->next;p;){ p = p->next = copy->next; copy = copy->next = (p?p->next:NULL); } return head; } };
转载于:https://www.cnblogs.com/vercont/p/10210286.html
相关资源:JAVA上百实例源码以及开源项目