138. 随机链表的复制
最近更新:2025-03-26 | 字数总计:226 | 阅读估时:1分钟 | 阅读量:次
- 解析
- hash表
- 利用链表指针,无需额外空间
Problem: 138. 随机链表的复制
解析
hash表
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
| class Solution { public: Node *copyRandomList(Node *head) { if (head == nullptr) { return nullptr; } Node *res = new Node(head->val); Node *node1 = head; Node *node2 = res; unordered_map<Node *, Node *> hashTable;
while (node1 != nullptr && node1->next != nullptr) { hashTable.insert({node1, node2}); node2->next = new Node(node1->next->val); node1 = node1->next; node2 = node2->next; } hashTable.insert({node1, node2});
node1 = head; node2 = res; while (node1 != nullptr) { if (node1->random != nullptr) { node2->random = hashTable[node1->random]; } node1 = node1->next; node2 = node2->next; } return res; } };
|
利用链表指针,无需额外空间
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
| class Solution { public: Node *copyRandomList(Node *head) { if (head == nullptr) { return nullptr; } Node *node = head; while (node != nullptr) { Node *temp = node->next; node->next = new Node(node->val); node->next->next = temp; node = temp; }
node = head; while (node != nullptr) { if (node->random != nullptr) { node->next->random = node->random->next; } node = node->next->next; }
node = head; Node *res = head->next; while (node != nullptr) { Node *temp = node->next; node->next = node->next->next; temp->next = node->next == nullptr ? nullptr : node->next->next; node = node->next; } return res; } };
|