给你两个单链表的头节点 headA
和 headB
,请你找出并返回两个单链表相交的起始节点。如果两个链表不存在相交节点,返回 null
。
解:哈希集合,用集合存储其中一个链表的所有元素,遍历另一个链表的元素时查看集合中是否存在该元素,如果存在则相交。
/**
* 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> 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;
}
}
解:A链表和B链表长度分别为 a 和 b ,假设存在相交链表且这公共部分的长度为 c ,建立两个 potinerA 和 potinerB ,这两个指针都是一个时间单位移动一长度,同时移动,potinerA走完了A链表后走B链表当走到公共部分时走了 a + (b - c),同理potinerB走完了B链表走A链表当走到公共部分时走了 b + (a - c),由于 a + (b - c) = b + (a - c),同时走到了公共节点。如果不存在相交链表,c为0,他们会同时走到null值。
思路:Krahets
/**
* 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) {
/*
* A链表长度为a,B链表长度存在b,假设存在公共部分长度为c
* a + b - c = b + a - c,如果存在则会相交,如果不存在c为0,都会同时走向null值
*/
ListNode potinerA = headA, potinerB = headB;
while(potinerA != potinerB){
potinerA = potinerA != null ? potinerA.next : headB;
potinerB = potinerB != null ? potinerB.next : headA;
}
return potinerA;
}
}