zoukankan      html  css  js  c++  java
  • leetcode138. 复制带随机指针的链表

    思路一:哈希

    借助哈希保存节点信息。

    代码

    时间复杂度:O(n)
    空间复杂度:O(n)

    class Solution{
    public:
        Node* copyRandomList(Node* head)
        {
            if(!head) return NULL;
            map<Node*,Node*>Map;
            //遍历链表,将原结点作为key,拷贝结点作为value保存在map
            Node* curr=head;
            while(curr)
            {
                Node* new_node=new Node(curr->val);
                Map[curr]=new_node;
                curr=curr->next;
            }
            //复制链表next和random指针
            curr=head;
            while(curr)
            {
                Map[curr]->next=Map[curr->next];
                Map[curr]->random=Map[curr->random];
                curr=curr->next;
            }
            return Map[head];
        }
    
    };

    2.原地复制

    1. 复制节点,同时将复制节点链接到原节点后面,如A->B->C 变为 A->A'->B->B'->C->C'。
    2. 设置节点random值。
    3. 将复制链表从原链表分离。
    class Solution {
    public:
        Node* copyRandomList(Node* head) {
            if (head == nullptr) {
                return head;
            }
            Node *node = head;
            //1. 将复制节点添加到原节点后面
            while (node != nullptr) {
                Node *copy = new Node(node->val, nullptr, nullptr);
                copy->next = node->next;
                node->next = copy;
                node = copy->next;
            }
            
            //2. 复制random节点
            node = head;
            while (node != nullptr) {
                if (node->random != nullptr) {
                    node->next->random = node->random->next;
                }            
                node = node->next->next;
            }
            
            //3. 分离链表
            node = head;
            Node *newHead = head->next;
            Node *newNode = newHead;
            while (node != nullptr) {
                node->next = node->next->next;     
                if (newNode->next != nullptr) {
                    newNode->next = newNode->next->next;            
                }            
                node = node->next;
                newNode = newNode->next;
            }
            return newHead;
        }
    };
  • 相关阅读:
    “人工智能”前景:只有人工,没有智能
    google scholar vs baidu scholar-what is your problem
    springSecurity使用
    springMVC中的HttpSession与Model
    mybatis关于Criteria的一点小坑。。。
    MyBatis的Mapper接口以及Example的实例函数及详解
    被springSecurity坑哭的一天
    Mybatis-Generator
    Redis五种数据类型应用场景
    springboot_自动配置原理
  • 原文地址:https://www.cnblogs.com/renzmin/p/11885301.html
Copyright © 2011-2022 走看看