【LeetCode】Copy List with Random Pointer
2014-04-24 16:18
274 查看
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.
思路:总共分为三个函数来解决,可以参照《剑指offer》4.4的26题。
①先复制所有的节点,把复制的节点直接挂到原始节点后面,所以每两个节点值就是一样的;
②然后将复制的节点的random指针指点前驱节点的random指针指向的下一个节点;
③拆分链表成两个。
Return a deep copy of the list.
思路:总共分为三个函数来解决,可以参照《剑指offer》4.4的26题。
①先复制所有的节点,把复制的节点直接挂到原始节点后面,所以每两个节点值就是一样的;
②然后将复制的节点的random指针指点前驱节点的random指针指向的下一个节点;
③拆分链表成两个。
/** * 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: void CloneList(RandomListNode *head){ RandomListNode *pNode=head; while(pNode!=NULL){ RandomListNode* tmp=new RandomListNode(pNode->label); //tmp->label=pNode->label; tmp->next=pNode->next; tmp->random=NULL; pNode->next=tmp; pNode=tmp->next; } } void CloneRandom(RandomListNode *head){ RandomListNode *pNodeold=head; while(pNodeold!=NULL){ if(pNodeold->random!=NULL){ pNodeold->next->random=pNodeold->random->next; } pNodeold=pNodeold->next->next; } } RandomListNode *DevideList(RandomListNode *head){ RandomListNode *pNodeold=head; RandomListNode *headnew=NULL; RandomListNode *pNodenew=NULL; if(pNodeold!=NULL){ headnew=pNodenew=head->next; pNodeold->next=pNodenew->next; pNodeold=pNodeold->next; } while(pNodeold!=NULL){ pNodenew->next=pNodeold->next; pNodenew=pNodenew->next; pNodeold->next=pNodenew->next; pNodeold=pNodeold->next; } return headnew; } RandomListNode *copyRandomList(RandomListNode *head) { if(head==NULL)return NULL; CloneList(head); CloneRandom(head); return DevideList(head); } };
相关文章推荐
- [LeetCode] Copy List with Random Pointer
- 【LeetCode-面试算法经典-Java实现】【138-Copy List with Random Pointer(拷贝有随机指针的单链表)】
- [LeetCode][JavaScript]Copy List with Random Pointer
- [leetcode] Copy List with Random Pointer, Java
- [LeetCode] Copy List with Random Pointer
- LeetCode OJ Copy List with Random Pointer
- Leetcode Copy List with Random Pointer
- LeetCode题解:Copy List with Random Pointer
- LeetCode(138) Copy List with Random Pointer
- [LeetCode]题解(python):138-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[138] Copy List with Random Pointer
- LeetCode: Copy List with Random Pointer
- LeetCode – Refresh – Copy List with Random Pointer
- LeetCode Copy List with Random Pointer