138. Copy List with Random Pointer--Medium

Posted xuyy-isee

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了138. Copy List with Random Pointer--Medium相关的知识,希望对你有一定的参考价值。

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.

Example 1:

Input:
"$id":"1","next":"$id":"2","next":null,"random":"$ref":"2","val":2,"random":"$ref":"2","val":1

Explanation:
Node 1‘s value is 1, both of its next and random pointer points to Node 2.
Node 2‘s value is 2, its next pointer points to null and its random pointer points to itself.

Note:

You must return the copy of the given head as a reference to the cloned list.

1.思考

  • 在《剑指offer》中有相同的题目;
  • 分为三步:
    (1). 先在每个原节点后复制copy的节点,即改变next节点;
    (2). 再根据原节点random的指向确定copy节点的random指向;
    (3). 最后将原list和copy的list分离;
    技术图片

  • 这题充分说明了list不利于查找的缺点,但同时能够让我们很好地掌握list指针的相关知识点。

2.实现
Runtime: 32ms(74.43%)
Memory: 21.9MB(100%)

/*
// Definition for a Node.
class Node 
public:
    int val;
    Node* next;
    Node* random;

    Node() 

    Node(int _val, Node* _next, Node* _random) 
        val = _val;
        next = _next;
        random = _random;
    
;
*/
class Solution 
public:
    Node* copyRandomList(Node* head) 
        if(head == NULL)
            return NULL;
        
        //第一步先复制节点,即确定next节点
        Node *curNode = head;
        while(curNode!=NULL)
            Node *copyNode = new Node(curNode->val, curNode->next, NULL);
            curNode->next = copyNode;
            curNode = copyNode->next;
        
        //第二步再确定random指向
        curNode = head;
        while(curNode!=NULL)
            if(curNode->random!=NULL)
                curNode->next->random = curNode->random->next;
            
            else
                curNode->next->random = NULL;
            curNode = curNode->next->next;
        
        //第三步将copy的list分离
        curNode = head;
        Node *copyHead = head->next;
        while(curNode!=NULL)
            Node *copyNode;
            copyNode = curNode->next;
            curNode->next = copyNode->next;
            if(copyNode->next!=NULL)
                copyNode->next = curNode->next->next;
            else
                copyNode->next = NULL;
            curNode = curNode->next;
        
        return copyHead;
    
;

以上是关于138. Copy List with Random Pointer--Medium的主要内容,如果未能解决你的问题,请参考以下文章

138. Copy List with Random Pointer

138. Copy List with Random Pointer

138 Copy List with Random Pointer

138. Copy List with Random Pointer

138. Copy List with Random Pointer(js)

138. Copy List with Random Pointer