题目
Write a program to find the node at which the intersection of two singly linked lists begins.
For example, the following two linked lists:
A: a1 → a2
↘
c1 → c2 → c3
↗
B: b1 → b2 → b3
总结
思路一:把listA存入hashMap中,按顺序匹配第一个listB中存在于listA的节点,即为交界点
代码:
/**
* 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 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;
}
}
思路二:
假设listA和listB有交点
把listA交点分为两段,分别长为X和Y
listB也按交点分为两段,分别长为Z和W,相交后的长度肯定相同,即W = Y
对两个list分别按 L1:listA->listB 和 L2:listB->listA遍历
对于L1在达到交点时,链表遍历了X + Y + Z个点
对于L2在达到交点时,链表遍历了Z + W + X = Z + Y + X = X + Y + Z,和L1遍历了相同个数的点。那么我们可以用两个指针对L1和L2同步遍历,指针指向同一个点时即为交点
代码:
/**
* 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 currentA = headA;
ListNode currentB = headB;
while (currentA != currentB) {
if (currentA == null) {
currentA = headB;
} else {
currentA = currentA.next;
}
if (currentB == null) {
currentB = headA;
} else {
currentB = currentB.next;
}
}
return currentA;
}
}