Leetcode: Copy List with Random Pointer - 再解
2014-05-26 13:55
288 查看
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.
一种逻辑更清楚的方法:1)复制每个节点并插入到当前节点之后;2)根据当前节点和复制节点直接相邻这个关系设置random指针,copied->random = cur->random->next;3)拆分这个链表为2个记得复制后的链表。
Return a deep copy of the list.
一种逻辑更清楚的方法:1)复制每个节点并插入到当前节点之后;2)根据当前节点和复制节点直接相邻这个关系设置random指针,copied->random = cur->random->next;3)拆分这个链表为2个记得复制后的链表。
/** * 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: RandomListNode *copyRandomList(RandomListNode *head) { if (head == NULL) { return head; } RandomListNode *cur = head; RandomListNode *next = NULL; RandomListNode *tmp; while (cur != NULL) { next = new RandomListNode(cur->label); tmp = cur->next; cur->next = next; cur = tmp; next->next = cur; } cur = head; while (cur != NULL) { if (cur->random != NULL) { cur->next->random = cur->random->next; } cur = cur->next->next; } RandomListNode *copied = new RandomListNode(0); tmp = copied; cur = head; while (cur != NULL) { copied->next = cur->next; copied = copied->next; cur->next = copied->next; cur = cur->next; } copied = tmp->next; delete tmp; return copied; } };
相关文章推荐
- Copy List with Random Pointer 复制有随机指针的链表@LeetCode
- [leetcode]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, Solution
- leetcode 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
- [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 -- Copy List with Random Pointer
- LeetCode:Copy List with Random Pointer
- LeetCode(138)Copy List with Random Pointer
- [LeetCode]Copy List with Random Pointer
- leetcode - Copy List with Random Pointer