当前位置:网站首页>【剑指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;
}
};
边栏推荐
- 解决方法:STM32使用cJSON解析数据失败
- Course design for the end of the semester: product sales management system based on SSM
- MySQL8 NDB Cluster安装部署
- 自旋锁探秘
- leetcode:1042. Do not plant flowers adjacent to each other [randomly fill in qualified + no contradiction will be formed behind + set.pop]
- leetcode:787. K 站中转内最便宜的航班【k步最短路 + dfs记忆化 + defaultdict(dict)】
- 网络:服务器网卡组技术原理与实践
- Consolidate entry-C basic variables and constants
- Development: how to install offline MySQL in Linux system?
- 美国穆格moog伺服阀D661-4577C
猜你喜欢

Six pictures show you why TCP has three handshakes?

Course design for the end of the semester: product sales management system based on SSM

Acwing game 57

Hyper-V: enable SR-IOV in virtual network

parker变量柱塞泵PV092R1K1T1NMMC

New skill: accelerate node through code cache JS startup

More than 20million videos have been played in the business list! Why is the reform of Agricultural Academies urged repeatedly?

Property or method “approval1“ is not defined on the instance but referenced during render

中基协:推荐使用电子合同

Cesium-1.72 learning (China national boundary)
随机推荐
nodejs学习笔记二
Interview shock 60: what will cause MySQL index invalidation?
Six photos vous montrent pourquoi TCP serre la main trois fois?
[C language] explain threads - thread separation function pthread_ detach
Acwing game 57
Canvas mouse control gravity JS effect
Bridge emqx cloud data to AWS IOT through the public network
5G商用三年,未来创新何去何从?
期未课程设计:基于SSM的产品销售管理系统
canvas云朵形状动画
Exch:exchange server 2013 is about to end support
MySQL advanced notes
美国穆格moog伺服阀D661-4577C
leetcode:1042. Do not plant flowers adjacent to each other [randomly fill in qualified + no contradiction will be formed behind + set.pop]
Rexroth hydraulic control check valve z2s10-1-3x/
Parker proportional overflow valve rs10r35s4sn1jw
MOOG servo valve d661-4577c
Property or method “approval1“ is not defined on the instance but referenced during render
NielsenIQ迎来零售实验室负责人Dawn E. Norvell,将加速扩张全球零售战略
Pref usage record