138. Copy List with Random Pointer
欢迎fork and star:Nowcoder-Repository-github
138. 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.
解析
-
在原链表的每个节点后面拷贝出一个新的节点
-
依次给新的节点的随机指针赋值,而且这个赋值非常容易 cur->next->random = cur->random->next
-
断开链表可得到深度拷贝后的新链表
-
几个易错点:
-
插入在当前节点前或者后要分清
-
copy random 指针->next理解,就是当前copy节点的random节点指向当前cur节点的random节点的下一个节点
-
分离链表是否加头结点,不加也可以吧,指针分离都要连起来
/**
* 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)
return NULL;
//if (!head->next) //bug: 这句话bug,不加才行!!!
//{
// RandomListNode* copy = new RandomListNode(head->label);
// return copy;
//}
RandomListNode* cur = head;
RandomListNode* temp = NULL;
while (cur) //在每个节点后面copy节点
{
RandomListNode* newNode = new RandomListNode(cur->label); //bug 在之后插入
temp = cur->next;
cur->next = newNode;
newNode->next = temp;
cur = cur->next->next;
}
//每个节点copy random指针
cur = head;
while (cur) //bug 指针越界
{
if (cur->random)
{
cur->next->random = cur->random->next; //??->next
}
cur=cur->next->next;
}
// 将original list和copy list分开
cur = head;
RandomListNode* copyHead = new RandomListNode(0);
RandomListNode* copy_cur = copyHead;
RandomListNode* next = NULL;
while (cur)
{
next = cur->next->next;
copy_cur->next = cur->next;
copy_cur = cur->next;
cur->next = next;
cur = next;
}
return copyHead->next;
/*RandomListNode*p = NULL;
p = head;
RandomListNode* res = head->next;
while (p->next != NULL)
{
RandomListNode* tmp = p->next;
p->next = p->next->next;
p = tmp;
}
return res; */
}
};
题目来源
C/C++基本语法学习
STL
C++ primer