LeetCode — Copy List with Random Pointer 解题报告
2013-12-26 10:06
561 查看
转载请注明:http://blog.csdn.net/ict2014/article/details/17577191
原题如下:
题目解析:
这道题目是“复杂链表的复制”。很经典的一道题目,可以从网上进行搜索,比如可以参考这篇文章:复杂链表复制。
我们按照传统的做法进行解题。总共分为三步:
1、申请结点并且连接成一个链表
2、random pointer的赋值
3、拆分链表成两个链表
题目代码:
原题如下:
题目解析:
这道题目是“复杂链表的复制”。很经典的一道题目,可以从网上进行搜索,比如可以参考这篇文章:复杂链表复制。
我们按照传统的做法进行解题。总共分为三步:
1、申请结点并且连接成一个链表
2、random pointer的赋值
3、拆分链表成两个链表
题目代码:
/** * 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) { RandomListNode* new_head = NULL; if(head == NULL){ return new_head; } //copy and connect CopyAndConnect(new_head, head); //set the random SetRandom(head); //split into two list SplitToTwoLists(head); return new_head; } //copy the list to new list //connect the two lists void CopyAndConnect(RandomListNode* &new_head, RandomListNode* head){ bool first = true; RandomListNode* next, *new_node; while(head != NULL){ next = head->next; new_node = new RandomListNode(head->label); new_node->next = next; head->next = new_node; if(first){ new_head = new_node; first = false; } head = next; } } //set the random void SetRandom(RandomListNode* head){ while(head != NULL){ if(head->random != NULL){ head->next->random = head->random->next; } head = head->next->next; } } //split into two list void SplitToTwoLists(RandomListNode* head){ RandomListNode* next; while(head != NULL){ next = head->next; head->next = next->next; if(next->next == NULL){ next->next = NULL; }else{ next->next = next->next->next; } head = head->next; } } };
相关文章推荐
- leetCode解题报告之Copy List with Random Pointer
- JAVA学习44_leetCode解题报告之Copy List with Random Pointer
- 【LeetCode】Copy List with Random Pointer 解题报告
- LeetCode 解题报告 Copy List With Random Pointer
- 【原创】leetCodeOj --- Copy List with Random Pointer 解题报告
- leetcode解题笔记-Copy List with Random Pointer
- Copy List with Random Pointer的解题报告
- LeetCode(138) 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
- Copy List with Random Pointer leetcode java
- leetcode - Copy List with Random Pointer
- leetcode:Copy List with Random Pointer 细致分析,以及代码实现(JAVA版本)
- leetcode做题总结,题目Copy List with Random Pointer 2013/10/03
- leetcode之Copy List with Random Pointer
- leetcode 149: Copy List with Random Pointer
- leetcode[138] Copy List with Random Pointer