22.相交链表
给定两个单链表的头节点 headA 和 headB ,请找出并返回两个单链表相交的起始节点。如果两个链表没有交点,返回 null 。
题目数据 保证 整个链式结构中不存在环。注意,函数返回结果后,链表必须 保持其原始结构 。

输入:intersectVal = 8, listA = [4,1,8,4,5], listB = [5,0,1,8,4,5], skipA = 2, skipB = 3 输出:Intersected at '8' 解释:相交节点的值为 8 (注意,如果两个链表相交则不能为 0)。 从各自的表头开始算起,链表 A 为 [4,1,8,4,5],链表 B 为 [5,0,1,8,4,5]。 在 A 中,相交节点前有 2 个节点;在 B 中,相交节点前有 3 个节点。
思路:
遍历一遍A,节点都存入哈希
再遍历B,如果B中节点在哈希中contains(node),返回该节点,都不在return null;
1 /** 2 * Definition for singly-linked list. 3 * public class ListNode { 4 * int val; 5 * ListNode next; 6 * ListNode(int x) { 7 * val = x; 8 * next = null; 9 * } 10 * } 11 */ 12 public class Solution { 13 public ListNode getIntersectionNode(ListNode headA, ListNode headB) { 14 Set<ListNode> visited = new HashSet<ListNode>(); 15 ListNode temp = headA; 16 while(temp!=null){ 17 visited.add(temp); 18 temp=temp.next; 19 } 20 21 temp=headB; 22 while(temp!=null){ 23 if(visited.contains(temp)){ 24 return temp; 25 } 26 temp=temp.next; 27 } 28 return null; 29 30 } 31 }

浙公网安备 33010602011771号