题目描述
输入一个复杂链表(每个节点中有节点值,以及两个指针,一个指向下一个节点,另一个特殊指针random指向一个随机节点),请对此链表进行深拷贝,并返回拷贝后的头结点。(注意,输出结果中请不要返回参数中的节点引用,否则判题程序会直接返回空)
思路:
python
# -*- coding:utf-8 -*-
# class RandomListNode:
# def __init__(self, x):
# self.label = x
# self.next = None
# self.random = None
class Solution:
# 返回 RandomListNode
def Clone(self, pHead):
# write code here
if not pHead:
return None
cur = pHead
while cur:
tmp = RandomListNode(cur.label)
tmp.next = cur.next
cur.next = tmp
cur = tmp.next
cur = pHead
while cur:
tmp = cur.next
if cur.random:
tmp.random = cur.random.next
cur = tmp.next
cur = pHead
res = pHead.next
while cur.next:
tmp = cur.next
cur.next = tmp.next
cur = tmp
return res
c++
/*
*解题思路:
*1、遍历链表,复制每个结点,如复制结点A得到A1,将结点A1插到结点A后面;
*2、重新遍历链表,复制老结点的随机指针给新结点,如A1.random = A.random.next;
*3、拆分链表,将链表拆分为原链表和复制后的链表
*/
/*
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) return NULL;
nodeClone(pHead);
connectRandom(pHead);
return reconnect(pHead);
}
//[1]复制结点,插入到原结点后方
void nodeClone(RandomListNode *head)
{
RandomListNode *pNode = head;
while (pNode != NULL)
{
RandomListNode *pClone = new RandomListNode(pNode->label);
pClone->next = pNode->next;
pNode->next = pClone;
pNode = pClone->next;
}
}
//[2]还原新结点的random指针
void connectRandom(RandomListNode *head)
{
RandomListNode *pNode = head;
while (pNode != NULL)
{
RandomListNode *pClone = pNode->next;
if (pNode->random)
{
pClone->random = pNode->random->next;
}
pNode = pClone->next;
}
}
//[3]拆分
RandomListNode *reconnect(RandomListNode *head)
{
RandomListNode *pNode = head;
RandomListNode *result = head->next;
while (pNode != NULL)
{
RandomListNode *pClone = pNode->next;
pNode->next = pClone->next;
pNode = pNode->next;
if (pNode != NULL)
pClone->next = pNode->next;
}
return result;
}
};