Day001:Copy List with Random Pointer
来源:互联网 发布:网络军事评论员 编辑:程序博客网 时间:2024/05/21 12:12
Description: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.
Difficulty:如果是一个普通的单链表,我们只要按照顺序一点点复制节点及其next即可,但是当我们这样复制本文的random域时,其节点可能还没有复制出来,这样random就无法指向。
Solution:
1.先把节点一个个的复制出来并且把原来链表对应的节点的next指向这个节点,这样就可以复制出所有的节点,random域指针就可以指向正确的节点,如果原链表的next不指向新节点,那这样的节点就没有意义。
2.把新节点的random域指向它该指的节点,因为我们这时依然可以遍历原链表,当得到原节点random域指向的指针后,可以直接让对应的新节点的random指向原节点random指向的节点对应的新节点,这样新节点random域就成功了。
3.把原节点的next指回原来的next指向节点,同时把新节点的next域也指向新节点,这样一个新的链表就复制完成了。
#include <iostream>#include <fstream>using namespace std;struct RandomListNode { int label; RandomListNode *next, *random; RandomListNode(int x) : label(x), next(NULL), random(NULL) {}};class Solution {public: RandomListNode *copyRandomList(RandomListNode * head) { RandomListNode * head_cp = nullptr, * cur = head, * cur_cp = nullptr; if (head == nullptr) return nullptr; while (cur != nullptr) { cur_cp = new RandomListNode (cur->label); cur_cp->next = cur->next; cur->next = cur_cp; cur = cur_cp->next; } cur = head; while (cur != nullptr) { cur_cp = cur->next; if (cur->random) cur_cp->random = cur->random->next; cur = cur_cp ->next; } cur = head; head_cp = head->next; while (cur != nullptr) { cur_cp = cur->next; cur->next = cur_cp->next; cur = cur->next; if (cur) cur_cp->next = cur->next; } return head_cp; }};
0 0
- Day001: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
- [Audacity][编译][步骤五]编译Audacity
- git 使用教程
- 第X大的数
- 10 多态 | 数组内容比较 | 单态模式
- 【PMP】Head First PMP 学习笔记 第九章 人力资源管理
- Day001:Copy List with Random Pointer
- 推导:从傅里叶级数展开到傅里叶变换
- 77:Convert Sorted List to Binary Search Tree
- js---初级知识点
- Android Studio查看自己的应用签名及三方APK签名信息
- Python与人工神经网络(4)——反向传播算法
- VPS 教程:Ubuntu 14.04 如何安装 Node.js 以及 Ghost 博客程序?
- 数据结构与算法之大数据处理
- Java中的hashmap