编写一个程序,找到两个单链表相交的起始节点。
/** * 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) {
ListNode* pa = headA;
ListNode* pb = headB;
ListNode* h;
int la=0,lb=0;
while(pa != NULL)
{
pa = pa->next;
++la;
}
while(pb !=NULL)
{
pb = pb->next;
++lb;
}
if(la == 0 || lb == 0)
return NULL;
if(la >= lb)
{
h = headA;
int c = la-lb;
while(c)
{
h = h->next;
c--;
}
while(h != NULL)
{
if(h != headB)
{
h = h->next;
headB = headB->next;
}
else break;
}
}
if(la < lb)
{
h = headB;
int c = lb-la;
while(c)
{
h = h->next;
c--;
}
while(h != NULL)
{
if(h != headA)
{
h = h->next;
headA = headA->next;
}
else break;
}
}
return h;
}
};
Vivi 2020-4-5