题目
我的题解
解法一:暴力
class Solution {
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
ListNode ha = headA;
while (ha != null) {
ListNode hb = headB;
while (hb != null) {
if (ha == hb) {
return ha;
} else {
hb = hb.next;
}
}
ha = ha.next;
}
return null;
}
}
解法二:哈希
class Solution {
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
Set<ListNode> ha = new HashSet<>();
while (headA != null) {
ha.add(headA);
headA = headA.next;
}
while (headB != null) {
if (ha.contains(headB)) {
return headB;
}
headB = headB.next;
}
return null;
}
}
其他题解
双指针法
考虑从两个链表开始移动指针,找到其重合,查看解法链接。