Please enable Javascript to view the contents

剑指office(二十五)复杂链表的复制

 ·  ☕ 1 分钟  ·  🎅 YSL

题目描述

输入一个复杂链表(每个节点中有节点值,以及两个指针,一个指向下一个节点,另一个特殊指针random指向一个随机节点),请对此链表进行深拷贝,并返回拷贝后的头结点。(注意,输出结果中请不要返回参数中的节点引用,否则判题程序会直接返回空)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
/*
struct RandomListNode {
    int label;
    struct RandomListNode *next, *random;
    RandomListNode(int x) :
            label(x), next(NULL), random(NULL) {
    }
};
*/
class Solution {
public:
    void Copy(RandomListNode* pHead)
    {
        RandomListNode* temp;
        while(pHead!=NULL)
        {
            temp = pHead->next;
            RandomListNode* pNode = new RandomListNode(pHead->label);
            pNode->next = temp;
            pNode->random = NULL;
            pHead->next = pNode;
            pHead = temp;
        }
    }
void AddRandom(RandomListNode* pHead)
{
    while (pHead!=NULL)
    {
        if(pHead->random!=NULL)
        {
            pHead->next->random = pHead->random->next;
        }
        if(pHead->next!=NULL)
            pHead = pHead->next->next;
    }
    
}

RandomListNode* Detch(RandomListNode* pHead)
{
    RandomListNode* pNode = pHead;
    RandomListNode* pCloneHead = NULL;
    RandomListNode* pClone = NULL;
    if(pNode != NULL){
        pCloneHead = pNode->next;
        pClone = pCloneHead;
        pNode->next = pCloneHead->next;
        pNode = pNode->next;
    }
    while (pNode!=NULL)
    {
        pClone->next = pNode->next;
        pClone = pClone->next;
        pNode->next = pClone->next;
        pNode = pNode->next;
        
    }
    return pCloneHead;
}
    RandomListNode* Clone(RandomListNode* pHead) {
        Copy(pHead);
        AddRandom(pHead);
        return Detch(pHead);
    }
};