题目:
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 * Definition for singly-linked list with a random pointer. 3 * struct RandomListNode { 4 * int label; 5 * RandomListNode *next, *random; 6 * RandomListNode(int x) : label(x), next(NULL), random(NULL) {} 7 * }; 8 */ 9 class Solution { 10 public: 11 RandomListNode *copyRandomList(RandomListNode *head) { 12 if(head == NULL) return NULL; 13 //将新节点复制到原来节点后面 14 RandomListNode *copy; 15 RandomListNode *p = head; 16 RandomListNode *tmp; 17 while(p!=NULL) 18 { 19 copy = new RandomListNode(p->label); 20 tmp = p->next; 21 p->next = copy; 22 copy->next = tmp; 23 p = tmp; 24 } 25 //将新结点与随机结点相连接 26 p = head; 27 copy = head->next; 28 while(p!=NULL && copy!=NULL) 29 { 30 copy->random = ((p->random)?p->random->next:NULL); 31 p = ((copy->next)?copy->next:NULL); 32 copy = ((p->next)?p->next:NULL); 33 } 34 //将新节点与原结点拆开 35 p = head; 36 head = copy = head->next; 37 while(p!=NULL && copy!=NULL) 38 { 39 p->next = ((copy->next)?copy->next:NULL); 40 p = ((p->next)?p->next:NULL); 41 copy->next = ((p)?p->next:NULL); 42 copy = ((copy->next)?copy->next:NULL); 43 } 44 return head; 45 } 46 };