LeetCode 138. Copy List with Random Pointer

题目描述:

A linked list is given such that each node contains an additional random pointer which could point to any node in the list or null.
Return a deep copy of the list.

解题思路:
我也不记得这道题在哪里看到过, 基本思路就是在原链表上复制每一个节点, 到原来节点的后面, 然后修复random pointers, 最后再将复制出来的节点, 从原链表中分离出来。

LeetCode 138. Copy List with Random Pointer_第1张图片
代码如下:

class Solution {
public:
    RandomListNode *copyRandomList(RandomListNode *head) {
        // 为每一个节点做一个备份, 插入原链表
        RandomListNode *pcur = head;
        while (pcur){
            RandomListNode * newNode = new RandomListNode(pcur->label);
            newNode->next = pcur->next;
            pcur->next = newNode;
            pcur = pcur->next->next;
        }

        // 复制random pointers
        pcur = head;
        while (pcur){
            RandomListNode * pNext = pcur->next;
            if (pcur->random)
                pNext->random = pcur->random->next;
            pcur = pcur->next->next;
        }

        // 分割链表
        RandomListNode myhead(0);
        RandomListNode * pre = &myhead;
        pcur = head;
        while (pcur){
            RandomListNode * pNext = pcur->next;
            pcur->next = pNext->next;           
            pcur = pcur->next;
            pre->next = pNext;
            pNext->next = nullptr;
            pre = pre->next;
        }

        return myhead.next;
    }
};

你可能感兴趣的:(LeetCode)