Algorithm/src/main/java/linkedlist/GetIntersectionNode.java
2025-03-14 20:12:38 +08:00

41 lines
1.2 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.

package linkedlist;
import java.util.HashSet;
/**
* 题目160. 相交链表 (getIntersectionNode)
* 描述:给你两个单链表的头节点 headA 和 headB ,请你找出并返回两个单链表相交的起始节点。如果两个链表不存在相交节点,返回 null 。
* 链接https://leetcode.cn/problems/intersection-of-two-linked-lists/
*/
//没想出高效方法
public class GetIntersectionNode {
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
HashSet<ListNode> visited = new HashSet<ListNode>();
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;
}
//高效方法
public ListNode getIntersectionNode1(ListNode headA, ListNode headB) {
ListNode A = headA, B = headB;
while (A != B) {
A = A != null ? A.next : headB;
B = B != null ? B.next : headA;
}
return A;
}
}