• 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;
        }
    };
    
  • 相关阅读:
    NSInternalInconsistencyException 关于iOS的背后线程刷新页面问题
    关于IOS UIlable 一行未满就换行
    ios 提交审核时出现二进制文件无效问题
    测试中缺陷等级分类
    测试的分类
    测试是一个纸杯
    如何测试一部电梯
    一个简单的测试案例
    【JVM】【常用工具】【MAT】macbook安装MAT(独立版,非eclipse插件)
    【Canal】【MySQL】解密阿里Canal :(一)Canal工作原理
  • 原文地址:https://www.cnblogs.com/xuyy-isee/p/11459755.html
Copyright © 2020-2023  润新知