剑指 Offer 52. 两个链表的第一个公共节点
使用双指针的方法,可以将空间复杂度降至 O(1)。只有当链表 headA headB都不为空时,两个链表才可能相交。因此首先判断链表 headA和 headB是否为空,如果其中至少有一个链表为空,则两个链表一定不相交,返回 null。
当链表 headA和 headB 都不为空时,创建两个指针pA 和pB,初始时分别指向两个链表的头节点 headA和 headB,然后将两个指针依次遍历两个链表的每个节点。具体做法如下:

package Linklist;import java.util.HashSet;
import java.util.Set;/*** @Classname JZ52两个链表的第一个公共节点* @Description TODO* @Date 2023/2/11 13:39* @Created by xjl*/
public class JZ52两个链表的第一个公共节点 {public class ListNode {int val;ListNode next;ListNode(int x) {val = x;next = null;}}// 采用的是双指针的方式ListNode getIntersectionNode(ListNode headA, ListNode headB) {if (headA == null || headB == null) {return null;}ListNode pA = headA;ListNode pB = headB;while (pA != pB) {pA = pA == null ? headB : pA.next;pB = pB == null ? headA : pB.next;}return pA;}// 使用的是双指针来实现ListNode getIntersectionNodecpoy(ListNode headA, ListNode headB) {if (headA==null|| headB==null){return null;}ListNode pA=headA;ListNode pB=headB;while (pA!=pB){pA=pA==null?headB:pA.next;pB=pB==null?headA:pB.next;}return pA;}}
判断两个链表是否相交,可以使用哈希集合存储链表节点。
如果链表 headB中的所有节点都不在哈希集合中,则两个链表不相交,返回 null。

public ListNode getIntersectionNode2(ListNode headA, ListNode headB) {Set visited = new HashSet();ListNode temp = headA;while (temp != null) {visited.add(temp);temp = temp.next;}temp = headB;while (temp != null) {if (visited.contains(temp)) {return temp;}temp = temp.next;}return null;}
《Leetcode》