LeetCode OJ - Copy List with Random Pointer
生活随笔
收集整理的這篇文章主要介紹了
LeetCode OJ - Copy List with Random Pointer
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
題目:
A linked list is given such that each node contains an additional random pointer which could point to any node in the list or null.
Return a deep copy of the list.
解題思路:
采用遞歸求解,并利用unordered_map來記錄新生成的節點。
代碼:
/*** Definition for singly-linked list with a random pointer.* struct RandomListNode {* int label;* RandomListNode *next, *random;* RandomListNode(int x) : label(x), next(NULL), random(NULL) {}* };*/ class Solution { public:unordered_map<int, RandomListNode*> dict;RandomListNode *copyRandomList(RandomListNode *head) {if (head == NULL || dict.count(head->label)) return NULL;RandomListNode *new_head = new RandomListNode(head->label);dict[head->label] = new_head;if (head->next != NULL) {copyRandomList(head->next);new_head->next = dict[head->next->label];}if (head->random != NULL) {copyRandomList(head->random);new_head->random = dict[head->random->label];}return new_head;} };?
轉載于:https://www.cnblogs.com/dongguangqing/p/3727129.html
總結
以上是生活随笔為你收集整理的LeetCode OJ - Copy List with Random Pointer的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 关于UI交互设计方面一些考虑的问题
- 下一篇: C++面试题:list和vector有什