题目链接
解题思路
双指针法
-
如下图所示,假设A,B为两个相交的链表,那么按照下面步骤计算
- 分别遍历两个链表,得到长度
lenA
和lenB
,假设 l e n A > l e n B lenA > lenB lenA>lenB,那么两个列表长度差为lenA - lenB
- 如图所示,将
curA
移动到和curB
对齐的位置 - 比较
curA == curB
,如果不相同,那么同时向后移动curA
和curB
,如果遇到相同的位置,则找到交点,否则循环退出返回空指针
- 分别遍历两个链表,得到长度
AC代码
public class Solution {
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
int lenA = 0;
int lenB = 0;
ListNode curA = headA;
ListNode curB = headB;
while(curA != null){
curA = curA.next;
lenA++;
}
while(curB != null){
curB = curB.next;
lenB++;
}
curA = headA;
curB = headB;
if(lenA > lenB){
int k = lenA - lenB;
for(int i = 0; i < k; i++){
curA = curA.next;
}
while(curA != null){
if(curA == curB){
return curA;
}
curB = curB.next;
curA = curA.next;
}
return null;
}
else{
int k = lenB - lenA;
for(int i = 0; i < k; i++){
curB = curB.next;
}
while(curB != null){
if(curA == curB){
return curA;
}
curB = curB.next;
curA = curA.next;
}
return null;
}
}
}