CS-Notes/notes/52. 两个链表的第一个公共结点.md
2019-11-02 17:33:10 +08:00

32 lines
1.3 KiB
Java
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# 52. 两个链表的第一个公共结点
[NowCoder](https://www.nowcoder.com/practice/6ab1d9a29e88450685099d45c9e31e46?tpId=13&tqId=11189&tPage=1&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking&from=cyc_github)
## 题目描述
<div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/5f1cb999-cb9a-4f6c-a0af-d90377295ab8.png" width="500"/> </div><br>
## 解题思路
A 的长度为 a + cB 的长度为 b + c其中 c 为尾部公共部分长度可知 a + c + b = b + c + a
当访问链表 A 的指针访问到链表尾部时令它从链表 B 的头部重新开始访问链表 B同样地当访问链表 B 的指针访问到链表尾部时令它从链表 A 的头部重新开始访问链表 A这样就能控制访问 A B 两个链表的指针能同时访问到交点
```java
public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) {
ListNode l1 = pHead1, l2 = pHead2;
while (l1 != l2) {
l1 = (l1 == null) ? pHead2 : l1.next;
l2 = (l2 == null) ? pHead1 : l2.next;
}
return l1;
}
```
<div align="center"><img width="320px" src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/githubio/公众号二维码-2.png"></img></div>