Skip to content

Commit

Permalink
week 3
Browse files Browse the repository at this point in the history
  • Loading branch information
lhj8 committed Oct 16, 2024
1 parent 1d4b1e0 commit b897020
Showing 1 changed file with 40 additions and 0 deletions.
40 changes: 40 additions & 0 deletions hj/week3/CopyLinkedListWithRandomPointer.cpp
Original file line number Diff line number Diff line change
@@ -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<Node*, Node*> 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];
}
};

0 comments on commit b897020

Please sign in to comment.