Copy List with Random Pointer [LeetCode]
2013-11-27 12:45
381 查看
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.
Solution: Uses map to recorde node mapping between old linked list and new linked list.
Return a deep copy of the list.
Solution: Uses map to recorde node mapping between old linked list and new linked list.
RandomListNode *copyRandomList(RandomListNode *head) { map<RandomListNode *, RandomListNode *> old_to_new; RandomListNode * current = head; RandomListNode * new_head = NULL; RandomListNode * pre = NULL; while(current != NULL) { RandomListNode * node = new RandomListNode(current->label); old_to_new[current] = node; if(new_head == NULL){ new_head = node; pre = node; }else if(pre != NULL){ pre->next = node; pre = pre->next; } current = current->next; } current = head; RandomListNode * new_current = new_head; while(current != NULL && new_current != NULL) { if(current->random != NULL) new_current->random = old_to_new[current->random]; else new_current->random = NULL; current = current->next; new_current = new_current->next; } return new_head; }
相关文章推荐
- [LeetCode]Copy List with Random Pointer
- leetcode — copy-list-with-random-pointer
- 138 Copy List with Random Pointer [Leetcode]
- 【LeetCode】Copy List with Random Pointer
- leetcode_Copy List with Random Pointer
- leetcode--011 copy list with random pointer
- leetcode做题总结,题目Copy List with Random Pointer 2013/10/03
- leetcode Copy List with Random Pointer
- [leetcode]Copy List with Random Pointer
- leetcode 149: Copy List with Random Pointer
- 【leetcode】Copy List with Random Pointer
- 【LeetCode】-Copy List with Random Pointer
- leetcode Copy List with Random Pointer
- 【LeetCode-面试算法经典-Java实现】【143-Copy List with Random Pointer(有随机指针的链表复制)】
- 【LeetCode】Copy List with Random Pointer
- LeetCode Copy List with Random Pointer
- leetcode — copy-list-with-random-pointer
- LeetCode--copy-list-with-random-pointer
- Copy List with Random Pointer -- leetcode
- Leetcode 138 Copy List with Random Pointer