博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
LeetCode. 复制带随机指针的链表
阅读量:2073 次
发布时间:2019-04-29

本文共 1525 字,大约阅读时间需要 5 分钟。

给定一个链表,每个节点包含一个额外增加的随机指针,该指针可以指向链表中的任何节点或空节点。

要求返回这个链表的****。

示例:

image

输入: {“KaTeX parse error: Expected '}', got 'EOF' at end of input: …":"1","next":{"id”:“2”,“next”:null,“random”:{“KaTeX parse error: Expected 'EOF', got '}' at position 9: ref":"2"}̲,"val":2},"rand…ref”:“2”},“val”:1}

解释: 节点 1 的值是 1,它的下一个指针和随机指针都指向节点 2 。

节点 2 的值是 2,它的下一个指针指向 null,随机指针指向它自己。

提示:

  1. 你必须返回给定头的拷贝作为对克隆列表的引用。
C++1

使用两次遍历+hash表。

/*// Definition for a Node.class Node {public:    int val;    Node* next;    Node* random;    Node() {}    Node(int _val, Node* _next, Node* _random) {        val = _val;        next = _next;        random = _random;    }};*/class Solution {
public: Node* copyRandomList(Node* head) {
unordered_map
nodemap; Node *temp = head; Node *new_head = new Node(0,NULL,NULL); Node *copy_temp = new_head; while(temp){
copy_temp->next = new Node(temp->val,NULL,NULL); nodemap[temp] = copy_temp->next; temp = temp->next; copy_temp = copy_temp->next; } Node * random_temp = NULL; temp = head; copy_temp = new_head->next; while(temp){
random_temp = temp->random; if(random_temp){
copy_temp->random = nodemap[random_temp]; }else{
copy_temp->random = NULL; } temp = temp->next; copy_temp = copy_temp->next; } return new_head->next; }};

转载地址:http://rlomf.baihongyu.com/

你可能感兴趣的文章
《redis设计与实现》 第一部分:数据结构与对象 || 读书笔记
查看>>
《redis设计与实现》 第二部分(第9-11章):单机数据库的实现
查看>>
算法工程师 面经2019年5月
查看>>
搜索架构师 一面面经2019年6月
查看>>
稻草人手记
查看>>
第一次kaggle比赛 回顾篇
查看>>
leetcode 50. Pow(x, n)
查看>>
leetcode 130. Surrounded Regions
查看>>
【托业】【全真题库】TEST2-语法题
查看>>
博客文格式优化
查看>>
【托业】【新托业全真模拟】疑难语法题知识点总结(01~05)
查看>>
【SQL】group by 和order by 的区别。
查看>>
【Python】详解Python多线程Selenium跨浏览器测试
查看>>
Jmeter之参数化
查看>>
Shell 和Python的区别。
查看>>
Python 列表(list)、字典(dict)、字符串(string)常用基本操作小结
查看>>
Loadrunner之https协议录制回放报错如何解决?(九)
查看>>
python中xrange和range的异同
查看>>
列表、元组、集合、字典
查看>>
【Python】easygui小甲鱼
查看>>