WHCSRL 技术网

138. 复制带随机指针的链表

138. 复制带随机指针的链表

题目描述

点这里

思路分析

链表操作练习
把每个节点的复制节点加到对应节点后边,这样可以节省一个哈希表

代码实现

/*
// Definition for a Node.
class Node {
public:
    int val;
    Node* next;
    Node* random;
    
    Node(int _val) {
        val = _val;
        next = NULL;
        random = NULL;
    }
};
*/

class Solution {
public:
    Node* copyRandomList(Node* head) {
        for(auto p=head;p;p=p->next->next){
            auto q=new Node(p->val);
            q->next=p->next;
            p->next=q;
        }

        for(auto p=head;p;p=p->next->next){
            if(p->random){
                p->next->random=p->random->next;
            }
        }

        auto dummy=new Node(-1);
        auto tail=dummy;
        for(auto p=head;p;p=p->next){
            auto q=p->next;
            tail=tail->next=q;
            p->next=q->next;
        }
        return dummy->next;
    }
};
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
推荐阅读