My 73ms C++ Solution for Intersection of Two Linked Lists


  • 0
    X
      class Solution {
    public:
        ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
    		if(headA==NULL || headB==NULL) return NULL;
            ListNode *pA=headA,*pB=headB,*ppA,*ppB;
    		int lenA=0,lenB=0;
    		while(pA!=NULL)
    		{
    			lenA++;
    			ppA = pA;
    			pA = pA->next;
    		}
    		while(pB!=NULL)
    		{
    			lenB++;
    			ppB = pB;
    			pB = pB->next;
    		}
    		if(ppB != ppA) return NULL;
    
    		if(lenB>lenA)
    		{
    			pA = headA;
    			pB = headB;
    			for(int i=0;i<(lenB-lenA);i++)
    			{
    				pB = pB->next;
    			}
    		}
    		else
    		{
    			pB = headB;
    			pA = headA;
    			for(int i=0;i<(lenA-lenB);i++)
    			{
    				pA = pA->next;
    			}
    		}
    
    		while(pB!=pA)
    		{
    			pA = pA->next;
    			pB = pB->next;
    		}
    
    		return pA;
    
        }
    };

  • 0
    C

    找不到ListNode在C++的说明...希望指点一下


  • 0
    W
        int lenA=1
        while(pA->next)
        {
           lenA++;
           pA = pA->next;
        }
    

    I think in this way , you can reduce one line of code ^_^


  • 0
    X

    you are right ^_^


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.