当前位置:网站首页>两个链表的第一个公共节点——LeetCode
两个链表的第一个公共节点——LeetCode
2022-08-10 23:55:00 【牛牛最爱喝兽奶】
力扣第 52题 两个链表的第一个公共节点
力扣题目描述
示例
读懂题意
这一道力扣题属于简单类型,读起题目也是很容易的,题目给的意思是开头是两个链表,结尾可能两链表会相遇,就是能找到两链表的公共部位,题目的要求就是我们必须找到公共结点的位置,并且返回。由示例一可以看出,值相等并非一定是公共结点。但是公共结点的值一定是相等的,所以我们只能从结点出发,判断链链表指向是否为同一结点。如果在链尾之前能找到公共结点,就返回公共结点,如果没有找到就返回为null。
解题思路
首先最简单最容易理解的一个思路,双层while循环,判断A链表当前结点与链表B结点是否相等,不相等A就往下一个结点移动,B接着判断,一直移到最后一个节点。因为两链表的长度不一定相等,所以移动的距离也不同,采用双层循环来处理!
解题代码
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { * val = x; * next = null; * } * } */
public class Solution {
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
ListNode a = headA;//获取A链表
ListNode b = headB;//获取B链表
while(a!=null){
//如果A链表还没有走到最后一个结点
b = headB;//每次从B链表的开头开始去遍历
while(b!=null){
//如果B还没有走到最后
if(b==a){
//如果找到则返回
return b;
}
b=b.next; //下一个B结点
}
a = a.next;//下一个A节点
}
return null;
}
}
边栏推荐
- “蔚来杯“2022牛客暑期多校训练营4 ADHK题解
- 线上突然查询变慢怎么核查
- 英文文献阅读时,如何做笔记?
- [C Language Chapter] Detailed explanation of bitwise operators (“<<”, “>>”, “&”, “|”, “^”, “~”)
- [21-day learning challenge - kernel notes] (5) - devmem read and write register debugging
- [Excel知识技能] 将“假“日期转为“真“日期格式
- What is the ASIO4ALL
- Summary of Confused Knowledge Points for "High Items" in the Soft Examination in the Second Half of 2022 (2)
- [C language] Detailed explanation of data storage
- 16. 文件上传
猜你喜欢
[Excel知识技能] 将文本型数字转换为数值格式
Which translation software is more accurate [Free]
Web-based meal ordering system in epidemic quarantine area
Which foreign language journals and conferences can be submitted for software engineering/system software/programming language?
"NIO Cup" 2022 Nioke Summer Multi-School Training Camp 2 DGHJKL Problem Solution
iNFTnews | Web3时代,用户将拥有数据自主权
promise详解
15. 拦截器-HandlerInterceptor
sqlmap结合dnslog快速注入
[C language] Implementation of guessing number game
随机推荐
力扣每日一题-第52天-387. 字符串中的第一个唯一字符
Call activity of Activiti7 sub-process
"NIO Cup" 2022 Nioke Summer Multi-School Training Camp 3 DF Problem Solving
特殊类与类型转换
UOJ#749-[UNR #6]稳健型选手【贪心,分治,主席树】
李彦宏拆墙交朋友,大厂“塑料友情”能否帮百度啃下硬骨头?
[Data Visualization] Chart Design Principles
[Excel knowledge and skills] Convert text numbers to numeric format
SAS数据处理技术(一)
Jvm.分析工具(jconsole,jvisualvm,arthas,jprofiler,mat)
ROS实验笔记之——安装QPEP以及Intel-MKL
SQL injection base - order by injection, limit, wide byte
App regression testing, what are the efficient testing methods?
Pagoda Test-Building PHP Online Mock Exam System
Design and Realization of Employment Management System in Colleges and Universities
Where can I download IEEE papers?
5. Lombok
多语种翻译-多语种翻译软件免费
三栏布局实现
PMP每日一练 | 考试不迷路-8.10(包含敏捷+多选)