##问题描述 Write a program to find the node at which the intersection of two singly linked lists begins.
查找交叉链表并得交叉节点,要求时间复杂度o(n)、空间复杂度o(1)
##解题思路 首先计算两个链表长度
然后长的链表向后移动直到保证两个链表长度相同
链表同时向后移动,如果相等则找到交叉节点,如果为空则表示没有交叉节点
##代码
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode *getIntersectionNode(struct ListNode *headA, struct ListNode *headB) {
int lenA = 0;
int lenB = 0;
struct ListNode *headATmp = headA;
struct ListNode *headBTmp = headB;
while (headATmp)
{
headATmp = headATmp->next;
lenA++;
}
while (headBTmp)
{
headBTmp = headBTmp->next;
lenB++;
}
if (lenA > lenB)
{
int offset = lenA - lenB;
while (offset--)
{
headA = headA->next;
}
}
else if (lenB > lenA)
{
int offset = lenB - lenA;
while (offset--)
{
headB = headB->next;
}
}
struct ListNode *intersectionNode = NULL;
while (headA)
{
if (headA == headB)
{
intersectionNode = headA;
break;
}
headA = headA->next;
headB = headB->next;
}
return intersectionNode;
}