From afb94e93bdd101f0390638c1aa8a65eb4765e8e4 Mon Sep 17 00:00:00 2001 From: Alessandro Cabassa <85694967+elcabalero@users.noreply.github.com> Date: Tue, 10 Jan 2023 22:49:18 +0100 Subject: [PATCH] Update copy-list-with-random-pointer.cpp as in the video Problem: 0138-copy-list-with-random-pointer.cpp Language: C++ Submission: https://leetcode.com/problems/copy-list-with-random-pointer/submissions/875731269/ --- cpp/0138-copy-list-with-random-pointer.cpp | 24 +++++++++++++++++++++- 1 file changed, 23 insertions(+), 1 deletion(-) diff --git a/cpp/0138-copy-list-with-random-pointer.cpp b/cpp/0138-copy-list-with-random-pointer.cpp index e280b11bd..09e431f70 100644 --- a/cpp/0138-copy-list-with-random-pointer.cpp +++ b/cpp/0138-copy-list-with-random-pointer.cpp @@ -55,7 +55,7 @@ class Node { // return visited[node]; // } // }; - +/* class Solution { public: Node* copyRandomList(Node* head) { @@ -99,3 +99,25 @@ class Solution { return oldHead; } }; +*/ + +class Solution { +public: + Node* copyRandomList(Node* head) { + unordered_map nodes; + Node* h = head; + + while (h){ + nodes[h] = new Node(h->val); + h = h->next; + } + h = head; + while (h){ + Node* newNode = nodes[h]; + newNode->next = nodes[h->next]; + newNode->random = nodes[h->random]; + h = h->next; + } + return nodes[head]; + } +};