LeetCode .面試題02.07. 鏈表相交-Venus

提示:

  1. 使用數學方法先記錄兩個鏈表的長度LA,LB,求差,將長的鏈表移動abs(LA-LB),後同時移動,相等即爲交點。時將複雜度爲O(N);

代碼:

/**
 * 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 countA = 0;
        int countB = 0;
        
        ListNode *ptrA = headA;
        ListNode *ptrB = headB;

        while(ptrA)
        {
            countA ++;
            ptrA = ptrA->next;
        }

        while(ptrB)
        {
            countB++;
            ptrB = ptrB->next;
        }

        ptrA = headA;
        ptrB = headB;
        
        if(countA > countB)
        {
            int dalta = countA - countB;
            while(ptrA && dalta--)
            {
                ptrA = ptrA->next;
            }
        }
        else
        {
            int dalta = countB - countA;
            while(ptrB && dalta--)
            {
                ptrB = ptrB->next;
            }
        }

        while(ptrA && ptrB)
        {
            if(ptrA == ptrB)
            {
                return ptrA;
            }
            ptrA = ptrA->next;
            ptrB = ptrB->next;

        }
        return NULL;
    }
};

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章