Algorithm/src/main/java/linkedlist/GetIntersectionNode.java

41 lines
1.2 KiB
Java
Raw Normal View History

2025-03-14 20:12:38 +08:00
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;
}
}