链表相交l
给你两个单链表的头节点 headA 和 headB ,请你找出并返回两个单链表相交的起始节点。如果两个链表没有交点,返回 null 。
图示两个链表在节点 c1 开始相交:
题目数据 保证 整个链式结构中不存在环。
注意,函数返回结果后,链表必须 保持其原始结构 。
示例 1:
输入:intersectVal = 8, listA = [4,1,8,4,5], listB = [5,0,1,8,4,5], skipA = 2, skipB = 3
输出:Intersected at ‘8’
解释:相交节点的值为 8 (注意,如果两个链表相交则不能为 0)。
从各自的表头开始算起,链表 A 为 [4,1,8,4,5],链表 B 为 [5,0,1,8,4,5]。
在 A 中,相交节点前有 2 个节点;在 B 中,相交节点前有 3 个节点。
题解
/**
* 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) {
int lenA = 0;
int lenB = 0;
//定义节点指向两个头节点
ListNode curA = headA;
ListNode curB = headB;
//统计链表A的元素个数
while(curA != null){
lenA++;
curA = curA.next;
}
//统计链表B的元素个数B
while(curB != null){
lenB++;
curB = curB.next;
}
//让curA和curB回归原位
curA = headA;
curB = headB;
//交换长度和节点
if(lenA < lenB){
//交换长度
int tempLen = lenA;
lenA = lenB;
lenB = tempLen;
//交换节点
ListNode temp = curA;
curA = curB;
curB = temp;
}
//计算差值
int grap = lenA - lenB;
//让A和B链表在同一起跑线上
while(grap -- > 0){
curA = curA.next;
}
//寻找相同节点
while(curA !=null){
if(curA == curB){
return curA;
}
curA = curA.next;
curB = curB.next;
}
return null;
}
}