题目:求两个链表公共结点
题目链接:
题目描述:编写一个程序,找到两个单链表相交的起始节点
输入: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 个节点。
思路:求出两个链表长度,如果一个链表长,就寻找下一个结点,让两个链表保持同一进度
代码:
import day0313.leetcode.ListNode;
public class Solution {
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
if (headA == null || headB == null) {
return null;
}
int countA = length(headA);
int countB = length(headB);
ListNode curA = headA;
ListNode curB = headB;
if (countA > countB) {
for (int i = 0; i < countA - countB; i++) {
curA = curA.next;
}
} else if (countA < countB) {
for (int i = 0; i < countB - countA; i++) {
curB = curB.next;
}
}
// 两个相遇 || 都 == null
while (curA != curB) {
curA = curA.next;
curB = curB.next;
}
return curA;
}
private int length(ListNode head) {
int count = 0;
for (ListNode cur = head; cur != null; cur = cur.next) {
count++;
}
return count;
}
}