1. 题目描述
给你两个单链表的头节点 headA 和 headB ,请你找出并返回两个单链表相交的起始节点。如果两个链表不存在相交节点,返回 null
2. 题解
public class Solution22 {
public static class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
next = null;
}
}
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
// 判断链表是否为空
if (headA == null || headB == null) {
return null;
}
// 初始化两个指针,分别指向两个链表的头节点
ListNode pointerA = headA;
ListNode pointerB = headB;
// 遍历链表
// 当 pointerA 或 pointerB 到达链表末尾时,将其重定位到另一个链表的头节点。这样可以确保两个指针在第二次遍历时能够同步到达相交节点或 null
while (pointerA != pointerB) {
pointerA = (pointerA == null) ? headB : pointerA.next;
pointerB = (pointerB == null) ? headA : pointerB.next;
}
return pointerA;
}
}