原题出处:https://leetcode.cn/leetbook/read/top-interview-questions-medium/xvdwtj/
解法一:
/**
* 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();
while (headA != null) {
set.add(headA);
headA = headA.next;
}
while (headB != null) {
if (set.contains(headB)) {
return headB;
}
headB = headB.next;
}
return null;
}
}
思路:题目的意思就是判断两个链表是否会相交,如果相交就返回相交的节点,否则返回null。解决的方法就是将一个链表的节点放到一个set中,然后在遍历另一个链表,如果set中存在当前链表的节点就直接返回,不存在就返回null即可。