面试题 02.07. 链表相交https://leetcode.cn/problems/intersection-of-two-linked-lists-lcci/
双指针法
1. 两个链表都不为空时:
设链表A的节点数为m,链表B的节点为n,两个链表相交的节点数为c,不相交的节点数分别为 a,b。
可以得到等式 。
定义两个指针pointA,pointB,分别指向headA,headB,两个指针分别遍历两个链表的所有节点。
1.1两个链表相交
- 当a=b时,两个指针会同时到达相交的节点,此时返回相交的节点。
- 当a≠b时,pointA会遍历完链表A,pointB会遍历完链表B。此时,pointA继续遍历链表B,pointB会继续遍历链表A。当pointA移动a+c+b次时,pointB移动b+c+a次时,两个指针同时指向相交的节点,返回相交的节点。
1.2两个链表不相交
两个链表不相交,则c=0
- a=b时,两个指针同时指向null,则返回null
- a≠b时,pointA会遍历完链表A和B,pointB会遍历完链表B和A,此时pointA移动的次数为m+n次,pointB移动的次数为n+m次。pointA和pointB同时指向null,此时返回null
2.两个链表有一个为空时返回null
最后附上代码
public ListNode getIntersectionNode2(ListNode headA, ListNode headB) {
if (headA==null || headB==null){
return null;
}
//定义两个指针
ListNode pointA=headA;
ListNode pointB=headB;
while (pointA!=pointB){
//pointA遍历链表A和B
pointA=pointA==null?headB:pointA.next;
//pointB遍历链表B和A
pointB=pointB==null?headA:pointB.next;
}
return pointA;
}