diff --git a/blogs/Algorithm/剑指 Offer/链表相关.md b/blogs/Algorithm/剑指 Offer/链表相关.md index 42a7196..3e38def 100644 --- a/blogs/Algorithm/剑指 Offer/链表相关.md +++ b/blogs/Algorithm/剑指 Offer/链表相关.md @@ -222,3 +222,45 @@ class Solution { } ``` +[52. 两个链表的第一个公共节点](https://leetcode-cn.com/problems/liang-ge-lian-biao-de-di-yi-ge-gong-gong-jie-dian-lcof/) + +```java +public class Solution { + public ListNode getIntersectionNode(ListNode headA, ListNode headB) { + ListNode h1 = headA; + ListNode h2 = headB; + while (h1 != null && h2 != null) { + if (h1 == h2) { + return h1; + } + h1 = h1.next; + h2 = h2.next; + if (h1 == null && h2 == null) { + return null; + } + if (h1 == null) { + h1 = headB; + } + if (h2 == null) { + h2 = headA; + } + } + return null; + } +} +``` + +```java +public class Solution { + public ListNode getIntersectionNode(ListNode headA, ListNode headB) { + ListNode h1 = headA; + ListNode h2 = headB; + while (h1 != h2) { + h1 = h1 == null ? headB : h1.next; + h2 = h2 == null ? headA : h2.next; + } + return h1; + } +} +``` +