LeetCode之Copy List with Random Pointer

来源:互联网 发布:软件测试工程师教程 编辑:程序博客网 时间:2024/05/17 08:04

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.

put the nodes in the original linked list to keep track of the order


                                                                                  (图片转自网络,如有侵犯,请告知)

/** * 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) {       if (head == NULL) return NULL;RandomListNode *p, *q;p = head;while (p){q = p->next;RandomListNode*node=new RandomListNode(p->label);node->next = q;p->next = node;p = q;}p = head;while (p){q = p->next;q->random = (p->random?p->random->next:NULL);p = q->next;}p = head;RandomListNode *copylist = p->next;while (p->next){q = p->next;p->next = q->next;p = q;}return copylist;    }};


0 0