当前位置:网站首页>【剑指Offer】52. 两个链表的第一个公共节点
【剑指Offer】52. 两个链表的第一个公共节点
2022-06-30 16:19:00 【LuZhouShiLi】
剑指 Offer 52. 两个链表的第一个公共节点
题目
输入两个链表,找出它们的第一个公共节点。
思路
使用两个指针Node1,node2,分别指向两个链表headA,headB的头节点,然后同时分别逐个节点遍历,当node1到达链表headA的末尾时,重新定位到链表headB的头节点,当node2到达链表headB的末尾时,重新定位到链表headA的头节点。
两个链表长度分别是L1 + C, L2 + C, C是公共部分长度,那么第一个指针走了L1 + C步之后,回到第二个链表的起点走L2步,第二个人走了L1步,当第二个人走的l2+C步之后,回到第一个人走L1步,当两个人走的步数都是L1 + L2 + C之后,就相遇了。
代码
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */
class Solution {
public:
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
ListNode *node1 = headA;
ListNode *node2 = headB;
while(node1 != node2)
{
node1 = node1 != NULL ? node1->next : headB;
node2 = node2 != NULL ? node2->next: headA;
}
return node1;
}
};
边栏推荐
- Plane intersection and plane equation
- 新技能:通过代码缓存加速 Node.js 的启动
- NielsenIQ迎来零售实验室负责人Dawn E. Norvell,将加速扩张全球零售战略
- Required plug-ins for idea
- 解决方法:STM32使用cJSON解析数据失败
- leetcode:787. K 站中转内最便宜的航班【k步最短路 + dfs记忆化 + defaultdict(dict)】
- Canvas cloud shape animation
- MySQL advanced notes
- Nichenet actual silicosis
- svg实现的订票UI效果
猜你喜欢
Compile u-boot source code for stm32p157 development board
6 張圖帶你搞懂 TCP 為什麼是三次握手?
【网易云信】播放demo构建:无法将参数 1 从“AsyncModalRunner *”转换为“std::nullptr_t”**
Acwing game 57
开发那些事儿:Linux系统中如何安装离线版本MySQL?
Implementation of graduation project management system based on SSM
Cesium-1.72 learning (earth rotation)
Hyper-v:在虚拟网络中启用 SR-IOV
Canvas cloud shape animation
浅析搭建高速公路视频监控平台的建设方案及必要性
随机推荐
Unity particle_ Exception display processing
Differential analysis between different groups nichenet for silicosis runs successfully!
MySQL advanced notes
Rexroth hydraulic control check valve z2s10-1-3x/
addmodule_ allmerge_ ams_ im
Course design for the end of the semester: product sales management system based on SSM
Hyper-v:在虚拟网络中启用 SR-IOV
Development: how to install offline MySQL in Linux system?
Develop those things: how to add text watermarks to videos?
Analysis on the construction scheme and necessity of constructing expressway video monitoring platform
. Net ORM framework hisql practice - Chapter 1 - integrating hisql
Shutter music recording playing audioplayers
More than 20million videos have been played in the business list! Why is the reform of Agricultural Academies urged repeatedly?
Redis elimination strategy
Bridge emqx cloud data to AWS IOT through the public network
Cesium-1.72 learning (China national boundary)
k线图精解与实战应用技巧(见位进场)
【Proteus仿真】Arduino UNO利用74LS148扩展中断
美国PARKER派克传感器P8S-GRFLX
数据分析新动力——国内首款开源一体化实时HTAP数据库石原子StoneDB发布