当前位置:网站首页>[sword finger offer] 52 The first common node of two linked lists
[sword finger offer] 52 The first common node of two linked lists
2022-06-30 17:40:00 【LuZhouShiLi】
The finger of the sword Offer 52. The first common node of two linked lists
subject
Enter two linked lists , Find their first common node .
Ideas
Using two Pointers Node1,node2, Point to two linked lists respectively headA,headB The head node of , Then traverse node by node at the same time , When node1 Reach the linked list headA At the end of , Relocate to the linked list headB The head node of , When node2 Reach the linked list headB At the end of , Relocate to the linked list headA The head node of .
The lengths of the two linked lists are L1 + C, L2 + C, C Is the length of the common part , So the first pointer goes L1 + C After step , Go back to the starting point of the second linked list L2 Step , The second man left L1 Step , When the second person left l2+C After step , Go back to the first person L1 Step , When two people take the same number of steps L1 + L2 + C after , Just met .
Code
/** * 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;
}
};
边栏推荐
猜你喜欢

4年工作经验,多线程间的5种通信方式都说不出来,你敢信?

【网易云信】播放demo构建:无法将参数 1 从“AsyncModalRunner *”转换为“std::nullptr_t”**

Write the simplest small program in C language Hello World

Canvas cloud shape animation

Servlet运行原理_API详解_请求响应构造进阶之路(Servlet_2)

广电5G正式启航,黄金频段将如何应用引关注

Six pictures show you why TCP has three handshakes?

flutter自定义组件

解决方法:STM32使用cJSON解析数据失败

Fragmentary knowledge points of MySQL
随机推荐
数据分析新动力——国内首款开源一体化实时HTAP数据库石原子StoneDB发布
js 从原型链到继承
parker变量柱塞泵PV092R1K1T1NMMC
Radio and television 5g officially set sail, attracting attention on how to apply the golden band
构建基本buildroot文件系统
Six photos vous montrent pourquoi TCP serre la main trois fois?
腾讯云的一场硬仗
splitting. JS password display hidden JS effect
编写C语言的最简单小程序Hello world
A tough battle for Tencent cloud
Hyper-V: enable SR-IOV in virtual network
[Netease Yunxin] playback demo build: unable to convert parameter 1 from "asyncmodalrunner *" to "std:: nullptr\u T"**
Property or method “approval1“ is not defined on the instance but referenced during render
flutter自定义组件
IEEE TBD SCI影响因子提升至4.271,位列Q1区!
知名互联网房屋租赁服务公司物联网关键业务迁移上云实践
EMQ helps Qingdao Yanbo build a smart water platform
Combination of applet container and Internet of things
splitting.js密码显示隐藏js特效
4 years of working experience, and you can't tell the five communication modes between multithreads. Can you believe it?