题目链接:
力扣https://leetcode-cn.com/problems/intersection-of-two-linked-lists/
【方法一】用哈希表存其中一条链的节点,在遍历第二条链的时候检查是否在哈希表中即可。
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;
}
}
【方法二】让两个链表头指针p、q一起跑,剩下没跑完的就是多出来的长度,让长的再跑这些长度,使二者对其,然后继续同时跑。
public class Solution {
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
ListNode p = headA, q = headB, r;
while(p != null && q!= null){
p = p.next;
q = q.next;
}
if(p != null) {
r = headA;
while(p != null){
p = p.next;
r = r.next;
}
q = headB;
while(r != null){
if(r == q) return r;
r = r.next;
q = q.next;
}
}else if(q != null){
r = headB;
while(q != null){
r = r.next;
q = q.next;
}
p = headA;
while(r != null){
if(r == p) return r;
r = r.next;
p = p.next;
}
}else{
p = headA;
q = headB;
while(p != null){
if(p == q) return p;
p = p.next;
q = q.next;
}
}
return null;
}
}
【方法三】这个方法真的特别好! “走到尽头见不到你,于是走过你来时的路,等到相遇时才发现,你也走过我来时的路。”
public class Solution {
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
ListNode p = headA, q = headB;
while(p != q){
p = p == null ? headB : p.next;
q = q == null ? headA : q.next;
}
return p;
}
}