编写一个程序,找到两个单链表相交的起始节点。
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
int getlen(struct ListNode *head)
{
int l = 0;
while(head)
{
l++;
head = head->next;
}
return l;
}
struct ListNode *getIntersectionNode(struct ListNode *headA, struct ListNode *headB) {
int a = getlen(headA);
int b = getlen(headB);
int i = 0;
if(a>b)
{
for(i=0; i<a-b; i++)
{
headA = headA->next;
}
}
else
{
for(i=0; i<b-a; i++)
{
headB = headB->next;
}
}
while(headA != headB && headA)
{
headA = headA->next;
headB = headB->next;
}
return headA;
}