题目链接:https://leetcode-cn.com/problems/intersection-of-two-linked-lists/submissions/
题目描述:
题目问题和难点:
1.是找相交的那个节点,而不是值相等的节点。(示例中1的值相同但不是相交的节点)
2.此题目不考虑有环的链表所以思路很简单。
public static ListNode getIntersectionNode(ListNode headA, ListNode headB) {
if(headA == null||headB==null){
return null;
}
//1.获取两个链表的长度
int lengthA = 0;
int lengthB = 0;
ListNode ACopy = headA;
ListNode BCopy = headB;
while(ACopy!=null){
ACopy = ACopy.next;
lengthA++;
}
while(BCopy!=null){
BCopy = BCopy.next;
lengthB++;
}
//2.找到两个链表长度的差值,并进行对齐。(长的链表多出来的长度去掉)
int dif = 0;
if(lengthA >lengthB){
dif = lengthA - lengthB;
while(headA!=null&&dif!=0){
headA = headA.next;
dif--;
}
}else{
dif = lengthB - lengthA;
while(headB!=null&&dif!=0){
headB = headB.next;
dif--;
}
}
//3.进行比较,节点相等返回
while(headA!=null&&headB!=null){
if(headA.val == headB.val){
return headA;
}else{
headA = headA.next;
headB = headB.next;
}
}
return null;
}