当前位置: 首页 > news >正文

【leetcode】138.复制带随机指针的链表

方法一:暴力求解

1️⃣遍历原链表,复制节点尾插

2️⃣更新random,原链表中的random对应第几个节点则复制链表中的random就对应第几个

📖Note

不能通过节点中的val判断random的指向,因为链表中可能存在两个val相等的节点

//创建节点
struct Node* BuyNode(int x)
{struct Node* newnode = (struct Node*)malloc(sizeof(struct Node));newnode->val = x;newnode->next = NULL;return newnode;
}//找到random对应的节点是第几个
int FindRandom(struct Node* head, struct Node* random)
{int count = 1;while (head){if (head == random){return count;}else {count++;head = head->next;}}return count;
}struct Node* copyRandomList(struct Node* head) {struct Node* guard = (struct Node*)malloc(sizeof(struct Node));guard->next = NULL;struct Node* tail = guard;struct Node* cur = head;//复制原链表while (cur){struct Node* newnode = BuyNode(cur->val);tail->next = newnode;tail = tail->next;cur = cur->next;}//tail和cur都指向新链表的头tail = guard->next;struct Node* tmp = head;//更新randomwhile (tail){//在原链表这种判断random指向的节点是第几个int count = FindRandom(head, tmp->random);tmp = tmp->next;//更新复制链表中的randomcur = guard->next;while (count--){tail->random = cur;if (cur){cur = cur->next;}}tail = tail->next;}struct Node* newhead = guard->next;free(guard);return newhead;}

方法二:

1️⃣拷贝原节点,并链接在原节点之后

2️⃣更新拷贝节点中的random

拷贝节点中的random指向的是原节点中random指向节点的下一个节点

3️⃣将拷贝的节点解下来构成新的复制链表

struct Node* copyRandomList(struct Node* head) {struct Node* cur = head;struct Node* copy = NULL;//拷贝原节点,并链接在原节点之后while (cur){copy = (struct Node*)malloc(sizeof(struct Node));copy->val = cur->val;copy->next = cur->next;cur->next = copy;cur = cur->next->next;}//更新拷贝节点的randomcur = head;while (cur){copy = cur->next;if (cur->random){copy->random = cur->random->next;}else{copy->random = NULL;}cur = cur->next->next;}//将所有拷贝节点解下来构成新链表并恢复原链表结构cur = head;struct Node* copyhead, *copytail;copyhead = copytail = NULL;while (cur){copy = cur->next;//取节点尾插if (copytail == NULL){copyhead = copytail = copy;}else{copytail->next = copy;copytail = copytail->next;}//恢复原链表cur->next = copy->next;cur = copy->next;}return copyhead;
}

http://www.lryc.cn/news/106088.html

相关文章:

  • svn工具使用
  • SpringBoot项目使用MyBatisX+Apifox IDEA 插件快速开发
  • Redis数据结构
  • 解密Redis:应对面试中的缓存相关问题
  • 读取application-dev.properties的中文乱码【bug】
  • Linux(centos7)如何实现配置iscsi存储多路径 及DM-Multipath的配置文件概述
  • DK7 vs JDK8 vs JDK11特性和功能的对比
  • 你觉得企业为什么需要数据分析?
  • SVN学习
  • vim怎么使用,vim使用教程,vimtutor怎么切换中文 汉化
  • [golang gin框架] 43.Gin商城项目-微服务实战之后台Rbac微服务之管理员的增删改查以及管理员和角色关联
  • 2023-07-31力扣每日一题
  • 接口自动化报告,生成本地服务并自动打开时失败
  • Git 的基本概念和使用方式
  • 【JVM】(三) 深入理解JVM垃圾回收机制(GC)
  • Flink CEP(二) 运行源码解析
  • 剑指Offer-学习计划(四)双指针(下)
  • 深度学习——常见注意力机制
  • Python 进阶(七):高级文件操作(shutil 模块)
  • 保留网络:大型语言模型的Transformer继任者
  • 算法通关村第二关——反转链表青铜笔记
  • 【Linux】——线程安全
  • [React]生命周期
  • 【2023】Redis实现消息队列的方式汇总以及代码实现
  • ARM裸机-10
  • 「C/C++」C/C++指针详解
  • 提高电脑寿命的维护技巧与方法分享
  • React常见面试题
  • C++中数据的输入输出介绍
  • 0101日志-运维-mysql