我们先看题目描述:
对于本题,带随机指针的链表,与我们常见的链表的唯一一个不同之处就在于,多了一个随机指针,我们是不知道它指向哪里的,所以我们可以分两步进行,先将该复杂链表的普通部分复制下来,但是单独复制的话我们无法去得知随机指针是指向的第几个节点,为了解决这个问题,我们将复制的节点依次插入到原链表中,就能很好的解决这个问题,我们用一张图来直观的感受一下
此时复制的链表就能通过它复制来的上一个节点找到它随机指针所应该指向的地方,被复制的节点为phead,复制的新节点为qhead,那么qhead->random = phead->random->next.就能很好的解决这个问题,而后我们只需将复制的新节点依次从上述链表中拆解下来即可。
代码如下:大家可以自行尝试一下
/**
* Definition for a Node.
* struct Node {
* int val;
* struct Node *next;
* struct Node *random;
* };
*/
//本题实现,未恢复原链表。
struct Node* copyRandomList(struct Node* head) {
struct Node* cur = head;
//先将该链表的普通模式复制,依次插入在其后。
while(cur){
struct Node* temp = (struct Node*)malloc(sizeof(struct Node));
temp->val = cur->val;
temp->next = cur->next;
cur->next = temp;
cur = cur->next->next;
}
cur = head;
//再在复制的节点中赋值random。
while(cur){
if(cur->random!=NULL)
cur->next->random = cur->random->next;
else
cur->next->random=NULL;
cur = cur->next->next;
}
//将新创建的链表取下来;
cur = head;
struct Node* phead = NULL,*tail = NULL;
while(cur){
if(tail==NULL){
phead = cur->next;
tail = cur->next;
cur = cur->next->next;
}
else{
tail ->next = cur->next;
tail = cur->next;
cur = cur->next->next;
}
}
//tail->next = NULL;
return phead;
}