auto commit
This commit is contained in:
24
docs/notes/52. 两个链表的第一个公共结点.md
Normal file
24
docs/notes/52. 两个链表的第一个公共结点.md
Normal file
@ -0,0 +1,24 @@
|
||||
# 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)
|
||||
|
||||
## 题目描述
|
||||
|
||||
<img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/5f1cb999-cb9a-4f6c-a0af-d90377295ab8.png" width="500"/>
|
||||
|
||||
## 解题思路
|
||||
|
||||
设 A 的长度为 a + c,B 的长度为 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;
|
||||
}
|
||||
```
|
Reference in New Issue
Block a user