版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/ghscarecrow/article/details/82048783
此题出自牛客网的剑指offer专题
题目描述
输入一个复杂链表(每个节点中有节点值,以及两个指针,一个指向下一个节点,另一个特殊指针指向任意一个节点),返回结果为复制后复杂链表的head。(注意,输出结果中请不要返回参数中的节点引用,否则判题程序会直接返回空)
解题思路
对于该题我们主要需要解决的问题其实就三个:节点值的复制,next指针的复制,随机指针的复制
对于该题,我们可以将其拆分成三步来解决。
1.复制原来链表的结点并将其放在被复制的结点之后,得到一条新的链表。比如说对结点A进行复制得到A1,再将A1放在A结点之后。
2.重新遍历链表,将老结点的随机指针复制给新结点,如:A1.random = A.random.next
3.拆分链表,将链表拆成原链表和复制好的链表
这里有一张图很好地说明了这个思路
代码如下
Java版本
/*
public class RandomListNode {
int label;
RandomListNode next = null;
RandomListNode random = null;
RandomListNode(int label) {
this.label = label;
}
}
*/
public class Solution {
public RandomListNode Clone(RandomListNode pHead){
if(pHead == null){
return null;
}
RandomListNode currentNode = pHead;
//完成节点值以及next指针的初步复制
while(currentNode != null){
RandomListNode cloneNode = new RandomListNode(currentNode.label);
RandomListNode nextNode = currentNode.next;
currentNode.next = cloneNode;
cloneNode.next = nextNode;
currentNode = nextNode;
}
//重新遍历链表,完成随机指针的复制
currentNode = pHead;
while(currentNode != null){
currentNode.next.random = currentNode.random==null? null:currentNode.random.next;
currentNode = currentNode.next.next;
}
//拆分链表
currentNode = pHead;
RandomListNode pCloneHead = pHead.next;
while(currentNode != null){
RandomListNode cloneNode = currentNode.next;
currentNode.next = cloneNode.next;
cloneNode.next = currentNode.next==null? null:currentNode.next.next;
currentNode = currentNode.next;
}
return pCloneHead;
}
}
C++版本
/*
struct RandomListNode {
int label;
struct RandomListNode *next, *random;
RandomListNode(int x) :
label(x), next(NULL), random(NULL) {
}
};
*/
class Solution {
public:
RandomListNode* Clone(RandomListNode* pHead)
{
if(pHead == NULL)
{
return NULL;
}
//复制原来的链表的结点,完成节点值和next指针的初步复制
RandomListNode* currentNode = pHead;
while(currentNode != NULL)
{
RandomListNode* cloneNode = new RandomListNode(currentNode->label);
RandomListNode* nextNode = currentNode->next;
currentNode->next = cloneNode;
cloneNode->next = nextNode;
currentNode = nextNode;
}
//完成节点的random指针的复制
currentNode = pHead;
while(currentNode != NULL)
{
currentNode->next->random = currentNode->random==NULL? NULL:currentNode->random->next;
currentNode = currentNode->next->next;
}
//拆分链表
currentNode = pHead;
RandomListNode* pCloneHead = pHead->next;
while(currentNode != NULL)
{
RandomListNode* cloneNode = currentNode->next;
currentNode->next = cloneNode->next;
cloneNode->next = cloneNode->next==NULL? NULL:cloneNode->next->next;
currentNode = currentNode->next;
}
return pCloneHead;
}
};