leetcode160相交链表

编写一个程序,找到两个单链表相交的起始节点。

leetcode160相交链表

/**
 * 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;
}

 

上一篇:leecode:剑指offer52 两个链表的第一个公共节点


下一篇:Intersection of Two Linked Lists