Find the list of the first common node

The first node seeking common list of the main ideas

There are two lists as follows:

There are two ways

  1. The link table, there is a brute force method, that is, each node with the list of additional nodes from a linked list to compare,
    if find the same node, which represents a common node, the algorithm time complexity is O (n * m), the length of the two lists, respectively n, m

  2. If the speed of the pointer, so long list pointer, go, the number of steps to go on, both the length difference, if they have the same node, bound in one place, to meet,
    the time complexity of the algorithm is O ( max (n, m))

The code is implemented method 2:

/*
struct ListNode {
    int val;
    struct ListNode *next;
    ListNode(int x) :
            val(x), next(NULL) {
    }
};*/
class Solution {
public:
    
    int lenOfList(ListNode* pHead){
        int len = 0;
        while( pHead != NULL){
            ++len;
            pHead = pHead->next;
        }
        return len;    
    }
    
    ListNode* FindFirstCommonNode( ListNode* pHead1, ListNode* pHead2) {
        if(pHead1 == NULL || pHead2 == NULL)
               return NULL;
        int len1,len2,k;
        ListNode *pFast=NULL,*pSlow=NULL;
        
        len1 = lenOfList(pHead1);
        len2 = lenOfList(pHead2);
        if(len1 >len2){
            pFast = pHead1;
            k = len1-len2;
            pSlow = pHead2;
        }else{
             pFast = pHead2;
             k = len2-len1;
             pSlow = pHead1;
        }
        int i=0;
        while(i<k){
            pFast = pFast->next;
            ++i;
        }
        
        while(pFast != NULL && pSlow != NULL){
            if(pFast == pSlow ){
                return pFast;
            }
            pFast = pFast->next;
            pSlow = pSlow->next;
            
        }
        return NULL;     
    }
};

Guess you like

Origin www.cnblogs.com/wanshuafe/p/11717400.html