Leetcode 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.

随机链表的节点数据结构

struct RandomListNode {
int label;
RandomListNode *next, *random;
RandomListNode(int x) : label(x), next(NULL), random(NULL) {}
};

注意本题是对带有随机链表指针的深度拷贝,

如果数据结构中那个没有随机指针,只需要将链表遍历拷贝一遍即可

但题目给的数据结构含有指针,拷贝后就必须保有随机指针的关系

本题通过在每个节点之后插入一个当前节点的拷贝节点,然后让插入的节点保有当前节点随机指针的关系,最后将插入的节点从链表中剥离出来即可

主要分为3步

(1)插入拷贝的节点

(2)复制random指针

(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) {
//copy list
RandomListNode *p = head;
while(p){
RandomListNode *tmp = new RandomListNode(p->label);
tmp->next = p->next;
p->next = tmp;
p = tmp->next;
}
//copy random pointer
RandomListNode *q = head;
while(q){
RandomListNode *tmp = q->next;
if(q->random){
tmp->random = q->random->next;
}
q=tmp->next;
}
//seperate list
RandomListNode *dupHead = head == NULL ? NULL : head->next, *cur = head;
while(cur){
RandomListNode *tmp = cur->next;
cur->next = tmp->next;
if(tmp->next){
tmp->next = tmp->next->next;
}
cur = cur->next;
}
return dupHead;
}
};
上一篇:iOS开发-二维码的基本使用


下一篇:java读取目录下所有csv文件数据,存入三维数组并返回