From b8970205512bba2d77e0ca01f3d327b485094cb8 Mon Sep 17 00:00:00 2001 From: Klaiden Date: Tue, 15 Oct 2024 19:52:27 -0700 Subject: [PATCH] week 3 --- hj/week3/CopyLinkedListWithRandomPointer.cpp | 40 ++++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 hj/week3/CopyLinkedListWithRandomPointer.cpp diff --git a/hj/week3/CopyLinkedListWithRandomPointer.cpp b/hj/week3/CopyLinkedListWithRandomPointer.cpp new file mode 100644 index 00000000..3d4b833a --- /dev/null +++ b/hj/week3/CopyLinkedListWithRandomPointer.cpp @@ -0,0 +1,40 @@ +/* +// 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) { + if (!head) return nullptr; + + unordered_map um; + + Node* crnt = head; + while (crnt) { + Node* node = new Node(crnt->val); + um[crnt] = node; + crnt = crnt->next; + } + + crnt = head; + while (crnt) { + um[crnt]->next = um[crnt->next]; + um[crnt]->random = um[crnt->random]; + crnt = crnt->next; + } + + return um[head]; + } +};