题目:
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.
/**
* 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 head;
RandomListNode *p = head;
//对每个节点进行复制,把新节点接在旧节点的下一个
while (p != NULL) {
RandomListNode *newNode = new RandomListNode(p->label);
newNode->next = p->next;
p->next = newNode;
p = newNode->next;
}
p = head;
//新节点的random指针为旧节点random指针的下一个或空
while (p != NULL) {
RandomListNode *newNode = p->next;
if(p->random != NULL)
newNode->random = p->random->next;
p = newNode->next;
}
p = head;
RandomListNode *newHead = head->next;
//将新旧链表拆分
while (p != NULL) {
RandomListNode *newNode = p->next;
p->next = newNode->next;
if (newNode->next != NULL)
newNode->next = newNode->next->next;
p = p->next;
}
return newHead;
}
};
本文介绍了一种解决复杂链表深拷贝问题的方法。这种链表的节点包含一个额外的随机指针,指向链表中的任意节点或空。通过巧妙地在原链表中插入新节点并调整指针,最终实现新旧链表的分离。
1290

被折叠的 条评论
为什么被折叠?



