Copy List with Random Pointer
来源:互联网 发布:java中的线程池 编辑:程序博客网 时间:2024/05/22 17:36
问题描述:
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.
解析:含有random 指针的链表复杂问题,由于在剑指offer上看过类似的题,所以很快就有解题思路。
1,,先复杂链表将复制节点插入到原节点的后面
2,复制random指针,将复制节点的random指针指向原节点的random的next,即指向了random的复制节点
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) { if(head == NULL) return NULL; RandomListNode *copyhead; RandomListNode *ptemp = head, *pnew = NULL; while(ptemp != NULL) //复制next { pnew = new RandomListNode(ptemp->label); pnew->next = ptemp->next; ptemp->next = pnew; ptemp = pnew->next; } ptemp = head;RandomListNode *pcopyhead = head->next, *pcopy = head->next; while(ptemp != NULL) //复制random { if( ptemp->random != NULL)pcopy->random = ptemp->random->next;ptemp = ptemp->next->next;if(pcopy->next == NULL) break;pcopy = pcopy->next->next;}ptemp = head;pcopyhead = pcopy = head->next;while(ptemp != NULL){ptemp->next = ptemp->next->next;if(pcopy->next == NULL) break;pcopy->next = pcopy->next->next;ptemp = ptemp->next;pcopy = pcopy->next;}return pcopyhead; }};
很多时候思路比努力更重要,选择对的方向才能更好的有解决方法。fight
0 0
- Copy List with Random Pointer
- Copy List with Random Pointer
- Copy List with Random Pointer
- Copy List with Random Pointer
- Copy List with Random Pointer
- Copy List with Random Pointer
- Copy List with Random Pointer
- Copy List with Random Pointer
- Copy List with Random Pointer
- Copy List with Random Pointer
- Copy List with Random Pointer
- Copy List with Random Pointer
- Copy List with Random Pointer
- Copy List with Random Pointer
- Copy List with Random Pointer
- Copy List with Random Pointer
- Copy List with Random Pointer
- Copy List with Random Pointer
- 自制操作系统--(9)
- u3d
- HOJ 题目分类
- 【无限互联】IOS开发之手势密码的实现
- 自己写操作系统--(10)
- Copy List with Random Pointer
- 自己写操作系统--(11)
- 麦田里的守望者
- 随机数
- 自己写操作系统--(12)
- G++(GNU C++)安装及使用(windows)
- 关于网站搭建的学习探索(
- http://localhost:8088/struts2_test2user/user/user/login
- 健康——每日饮水量建议