给你两个单链表的头节点 headA 和 headB ,请你找出并返回两个单链表相交的起始节点。如果两个链表没有交点,返回 null 。
图示两个链表在节点 c1 开始相交:
题目数据 保证 整个链式结构中不存在环。
注意,函数返回结果后,链表必须 保持其原始结构 。
示例 1:
示例 2:
示例 3:
思路:简单来说,就是求两个链表交点节点的指针。 这里要注意,交点不是数值相等,而是指针相等。我认为这道题还是使用双指针的精髓。
ListNode* getIntersectionNode(ListNode* headA, ListNode* headB) {
//用来准备统计A链表的长度:
ListNode* curA = headA;
//用来准备统计B链表的长度:
ListNode* curB = headB;
ListNode* pointA = headA;
ListNode* pointB = headB;
int sizeA = 0;
int sizeB = 0;
//统计链表A的长度
while (curA!=nullptr) {
sizeA++;
curA = curA->next;
}
//统计链表B的长度
while (curB != nullptr) {
sizeB++;
curB = curB->next;
}
//如果A的长度大于B的长度
if (sizeA > sizeB) {
// 求长度差
int n = sizeA - sizeB;
//pointA向前移动n个,指向A的头结点,与pointB齐平;(此时pointB指向B链表的头结点)
while (n && pointA != NULL) {
pointA = pointA->next;
n--;
}
//当pointA不等于pointB,且他俩都不为空;(这里比较的不是pointA B指向结点的数值,而是pointA B指针自身相等)
while (pointA != pointB && pointA != nullptr && pointB != nullptr) {
pointA = pointA->next;
pointB = pointB->next;
}
return pointA;
}
//如果B的长度大于A的长度,同理
else if (sizeA < sizeB) {
int n = sizeB - sizeA;
while (n && pointB != NULL) {
pointB = pointB->next;
n--;
}
while (pointA != pointB && pointA != nullptr && pointB != nullptr) {
pointA = pointA->next;
pointB = pointB->next;
}
return pointA;
}
//如果AB的长度相等,那就同时移动;
else {
while (pointA != pointB && pointA != nullptr && pointB != nullptr) {
pointA = pointA->next;
pointB = pointB->next;
}
return pointA;
}
}