/**
* 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) {
int l1(0),l2(0);
ListNode *p1=headA,*p2=headB;
while(p1)
{
++l1;
p1=p1->next;
}
while(p2)
{
++l2;
p2=p2->next;
}
if(l2>l1)
{
swap(l1,l2);
swap(headA,headB);
}
l1-=l2;
while(l1--)
{
headA=headA->next;
}
while(headA)
{
if(headA==headB) return headA;
headA=headA->next;
headB=headB->next;
}
return NULL;
}
};
leetcode - 160. Intersection of Two Linked Lists
最新推荐文章于 2022-08-06 10:20:24 发布