/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB)
{
if(headA==NULL || headB==NULL)
return NULL;
ListNode *node1=headA;
int length1=0;
while(node1!=NULL)
{
++length1;
node1=node1->next;
}
ListNode *node2=headB;
int length2=0;
while(node2!=NULL)
{
++length2;
node2=node2->next;
}
int diff=length1-length2;
if(diff<0)
{
node1=headA;
while(-diff)
{
headB=headB->next;
++diff;
}
node2=headB;
}
else
{
node2=headB;
while(diff)
{
headA=headA->next;
--diff;
}
node1=headA;
}
while(node1&&node2)
{
if(node1==node2)
return node1;
node1=node1->next;
node2=node2->next;
}
return NULL;
}
};
Intersection of Two Linked Lists
最新推荐文章于 2022-01-22 17:00:38 发布