剑指offer-复杂链表复制

题目:

输入一个复杂链表(每个节点中有节点值,以及两个指针,一个指向下一个节点,另一个特殊指针指向任意一个节点),返回结果为复制后复杂链表的head。(注意,输出结果中请不要返回参数中的节点引用,否则判题程序会直接返回空)

思路:

自己最开始是使用递归的方法,但是空间不够。随后用了一个分三步的方法:
(1)首先插入复制的节点到每一个原始节点之后,
(2)调节复制节点的random指针,
(3)调节原始节点和复制节点的next指针。

为什么要用这种思路的原因是:

在最简单的单链表复制中,我们只需要考虑一个指针的指向,但是多链表复制,我们在一个指针上完成新节点的创建后,在第二个指针的连接上,我们没有办法将新创建的节点和原始节点一一对应起来,所以该思路其实就解决了一一对应的问题(每一个原始节点对应新节点都是它之后的一个节点)。

代码如下
/*
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)    \\initial judge
            return NULL;
        RandomListNode* cur = pHead;
        while(cur){    //insert coppied node to the original node 
            RandomListNode* node = new RandomListNode(cur->label);
            node->next = cur->next;
            cur->next = node;
            cur = node->next;
        }
        cur = pHead;
        while(cur){//copy random pointer
            RandomListNode* node = cur->next;
            if(cur->random)
                node->random = cur->random->next;
            cur = node->next;
        }
        cur = pHead->next;
        RandomListNode* head = cur;
        RandomListNode* ocur = pHead;
        while(ocur){
            ocur->next = ocur->next->next;
            if(cur->next){
                cur->next = cur->next->next;
            }
            cur= cur->next;
            ocur = ocur->next;
        }
        return head;
    }
};

猜你喜欢

转载自blog.csdn.net/harry_128/article/details/80114552