题目
链接
题解
哈希表
import java.util.Set;
import java.util.HashSet;
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
Set<ListNode> set = new HashSet<>();
ListNode h1 = headA, h2 = headB;
while (h1 != null) {
set.add(h1);
h1 = h1.next;
}
while (h2 != null) {
if (set.contains(h2)) {
return h2;
}
h2 = h2.next;
}
return null;
}
}
双指针
import java.util.Set;
import java.util.HashSet;
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
ListNode h1 = headA, h2 = headB;
while (h1 != h2) {
h1 = h1 != null ? h1.next : headA;
h2 = h2 != null ? h2.next : headB;
}
return h1;
}
}