天天看點

【LeetCode】 160. Intersection of Two Linked Lists C語言

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
int list_length(struct ListNode *phead)
{
   int length=0;
   struct ListNode *pnode=phead;
   while(pnode != NULL)
   {
       length++;
       pnode=pnode->next;
   }
   return length;
}
struct ListNode *getIntersectionNode(struct ListNode *headA, struct ListNode *headB) {
    int A_length=list_length(headA);
    int B_length=list_length(headB);
    int gap_length=A_length>B_length?A_length-B_length:B_length-A_length;
    
    struct ListNode *plong=headA;
    struct ListNode *pshort=headB;
    
    if(A_length<B_length)
    {
        plong=headB;
        pshort=headA;
    }
    
    for(int i=0;i<gap_length;i++) plong=plong->next;  //長連結清單多走幾步
    
    while(plong && pshort && plong->val != pshort->val)
    {
        plong=plong->next;
        pshort=pshort->next;
    }
    return plong;
}
           

繼續閱讀