首页 > 代码库 > Copy List with Random Pointer
Copy List with Random Pointer
类同:剑指 Offer 题目汇总索引第26题
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, 拆分链表。
/** * 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 *head2, *p, *p2; p = head2 = head; while(p) { RandomListNode *s = new RandomListNode(p->label); s->next = p->next; p->next = s; p = s->next; } p = head; while(p) { if(p->random) p->next->random = p->random->next; p = p->next->next; } head2 = p2 = head->next; p = head; while(p) { p->next = p->next->next; p = p->next; if(p2->next) { p2->next = p2->next->next; p2 = p2->next; } } return head2; }};
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。