1. 程式人生 > >LeetCode(Copy List with Random Pointer) 複雜連結串列的深拷貝

LeetCode(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.

劍指offer上出現過這個題目,

思路是:

1.首先指向在原連結串列的每個節點後面,複製一個新的節點,原連結串列長度變為 2 倍random 指標指向的是 原連結串列節點 random 指標指向的節點的後面的那個節點。

2.將連結串列拆成兩個連結串列.


程式碼:

class Solution {
public:
    
    void CopyNodeAndRandomPointer(RandomListNode* head)
    {
        RandomListNode* node = head;
        while (NULL != node) {
            RandomListNode* new_node =  new RandomListNode(node->label);
            new_node->next = node->next;
            node->next = new_node;
            node = new_node->next;
        }
        //set random pointer
        node = head;
        while (NULL != node) {
            RandomListNode* pnext = node->next;
            if (NULL != node->random) {
                pnext->random = node->random->next;
            }
            node = pnext->next;
        }
    }
    
    RandomListNode* SeperateList(RandomListNode* head)
    {
        RandomListNode* node = head, *clone_head = NULL, *clone_node = NULL;
        if (NULL != node) {
            clone_head = clone_node = node->next;
            node->next = clone_node->next;
            node = node->next;
        }
        while (NULL != node) {
            clone_node->next = node->next;
            clone_node = clone_node->next;
            node->next = clone_node->next;
            node = node->next;
        }
        return clone_head;
    }
    
    RandomListNode *copyRandomList(RandomListNode *head) {
        CopyNodeAndRandomPointer(head);
        return SeperateList(head);
    }
};