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

刷题 链表

面试经典150题 - 链表

141. 环形链表

在这里插入图片描述

class Solution {
public:bool hasCycle(ListNode *head) {ListNode* slow = head, *fast = head;while (fast != nullptr && fast->next != nullptr) {slow = slow->next;fast = fast->next->next;if (slow == fast) {return true;}}return false;}
};

142. 环形链表 II

在这里插入图片描述

在这里插入图片描述

class Solution {
public:ListNode *detectCycle(ListNode *head) {ListNode* slow = head, *fast = head;while (fast != nullptr && fast->next != nullptr) {slow = slow->next;fast = fast->next->next;if (slow == fast) {slow = head;while (slow != fast) {slow = slow->next;fast = fast->next;}return slow;}}return nullptr;}
};

2. 两数相加 - 虚拟头节点 + 加法进位

在这里插入图片描述

class Solution {
public:ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {ListNode* dummy_head = new ListNode(0);ListNode* cur = dummy_head, *cur_1 = l1, *cur_2 = l2;int sum = 0, carry = 0;while (cur_1 || cur_2 || carry != 0) {sum = 0;if (cur_1) {sum += cur_1->val;cur_1 = cur_1->next;}if (cur_2) {sum += cur_2->val;cur_2 = cur_2->next;}sum += carry;carry = sum / 10;cur->next = new ListNode(sum % 10);cur = cur->next;}ListNode* head = dummy_head->next;delete dummy_head;dummy_head = nullptr;return head;}
};

21. 合并两个有序链表 - 虚拟头节点

在这里插入图片描述

class Solution {
public:ListNode* mergeTwoLists(ListNode* node_1, ListNode* node_2) {ListNode* dummy_head = new ListNode();ListNode* cur = dummy_head;while (node_1 != nullptr && node_2 != nullptr) {if (node_1->val < node_2->val) {cur->next = node_1;node_1 = node_1->next;} else {cur->next = node_2;node_2 = node_2->next;}cur = cur->next;}cur->next = node_1 ? node_1 : node_2; // 直接连接剩余部分ListNode* head = dummy_head->next;delete dummy_head;dummy_head = nullptr;return head;}
};

138. 随机链表的复制 - 深拷贝 - 哈希表存储对应关系

在这里插入图片描述

class Solution {
public:// 本题相当于 对 链表进行深拷贝Node* copyRandomList(Node* head) {unordered_map<Node*, Node*> copy_hash;Node* cur = head;// 先 根据节点的值 新建拷贝,并通过哈希表关联while (cur) {copy_hash[cur] = new Node(cur->val);cur = cur->next;}cur = head;// 根据哈希表 将 拷贝节点 连接起来 (next, random)while (cur) {copy_hash[cur]->random = copy_hash[cur->random];copy_hash[cur]->next = copy_hash[cur->next];cur = cur->next;}return copy_hash[head];}
};
http://www.lryc.cn/news/458055.html

相关文章:

  • SQL 语法学习指南
  • 低代码可视化-uniapp商城首页小程序-代码生成器
  • Vue3 富文本:WangEditor
  • Unity实现自定义图集(四)
  • k8s-pod的管理及优化设置
  • 软件测试面试题大全
  • SQL第16课挑战题
  • Python3 爬虫 中间人爬虫
  • Leetcode 50. Pow ( x , n ) 快速幂、取模 C++实现
  • Java SE vs Java EE 与 JVM vs JDK vs JRE
  • Linux YUM设置仓库优先级
  • 做一个不断更新的链接库
  • Ping32企业加密软件:保护数据安全
  • 【Java】异常的处理-方式【主线学习笔记】
  • React modal暴露ref简洁使用
  • 小米路由器ax1500+DDNS+公网IP+花生壳实现远程访问
  • 毕设分享 大数据用户画像分析系统(源码分享)
  • 使用 Redis 实现分布式锁:原理、实现与优化
  • Android常用C++特性之std::make_pair
  • Kafka-参数详解
  • Docker Overlay2 空间优化
  • 第 3 章:使用 Vue 脚手架
  • Spring 循环依赖详解:问题分析与三级缓存解决方案
  • 爬虫prc技术----小红书爬取解决xs
  • uni-app之旅-day06-加入购物车
  • 【Kubernetes】常见面试题汇总(五十六)
  • LabVIEW激光诱导击穿光谱识别与分析系统
  • Redis的基础篇
  • java和python哪个好
  • Electron + ts + vue3 + vite