Description

难度简单:剑指 Offer 52. 两个链表的第一个公共节点
输入两个链表,找出它们的第一个公共节点。
如下面的两个链表
剑指Offer 52. 两个链表的第一个公共节点 - 图1
在节点 c1 开始相交。

示例 1:
输入:intersectVal = 8, listA = [4,1,8,4,5], listB = [5,0,1,8,4,5], skipA = 2, skipB = 3
输出:Reference of the node with value = 8
输入解释:相交节点的值为 8 (注意,如果两个列表相交则不能为 0)。从各自的表头开始算起,链表 A 为 [4,1,8,4,5],链表 B 为 [5,0,1,8,4,5]。在 A 中,相交节点前有 2 个节点;在 B 中,相交节点前有 3 个节点。

Solution

首先,循环遍历得到两条链表的长度,计算两条链表的长度差,得到最长的链表,然后让最长的链表先走长度差的步数,使两条链表的长度相等,最后一起遍历两条链表,找到相交点。
/*
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 alen = 0, blen = 0;
ListNode nodeA = headA, nodeB = headB;
while(nodeA != null){ // 计算链表 A 的长度
alen ++;
nodeA = nodeA.next;
}
while(nodeB != null){ // 计算链表 B 的长度
blen ++;
nodeB = nodeB.next;
}
int count = alen - blen; // 计算链表 A 与链表 B 的长度差
ListNode few, more;
if ( count >= 0){
more = headA;
few = headB;
}else{
more = headB;
few = headA;
count = -count;
}
while ( (count—) > 0 ) // 长度长的链表先走 count 步,使两条链表的长度相等
more = more.next;
while( more != null && more != few){ // 找出相交点
more = more.next;
few = few.next;
}
return more;
}
}