Accepted solution, maybe not a good one,but with a simple thought


  • 0
    D

    The thought is to make the two lists's head pointers with the same distance to their tail. It means cutting the longer one by moving it's head pointer at first appropriately.

    Then move both pointer parallelly until the address are the same(return) or both move to the end with NULL return(if no interaction);

    /**
     * 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 Alen=0;
        int Blen=0;
        int i;
        ListNode *A,*B;
        A=headA;
        B=headB;
        
        while(A!=NULL)
            {
            Alen++;
            A=A->next;
            }
        while(B!=NULL)
            {
            Blen++;
            B=B->next;
            }
    
        A=headA;
        B=headB;
        
        if(Alen>Blen)
            for(i=0;i<Alen-Blen;i++)A=A->next;
        else
            for(i=0;i<Blen-Alen;i++)B=B->next;
        
        while(A!=NULL&&B!=NULL)
            if(A==B)
                return A;
            else
                {
                A=A->next;
                B=B->next;
                }
                
        return NULL;
    }
    

    };


  • 0
    C

    My java version. Same as yours. :)

        public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        int lenA = 0, lenB = 0;
        ListNode nodeA = headA;
        ListNode nodeB = headB;
        while(null != nodeA){
        	lenA ++;
        	nodeA = nodeA.next;
        }
        while(null != nodeB){
        	lenB ++;
        	nodeB = nodeB.next;
        }
        
        if(lenA > lenB){
        	nodeA = headA;
        	nodeB = headB;
        }
        else{
        	nodeA = headB;
        	nodeB = headA;
        }
        
        int diff = lenA > lenB ? lenA - lenB : lenB - lenA;
        for(int i = 0; i < diff; i ++){
        	nodeA = nodeA.next;
        }
        
        //start to compare.
        while(nodeA != null && nodeB != null){
        	if(nodeA == nodeB){
        		return nodeA;
        	}
        	nodeA = nodeA.next;
        	nodeB = nodeB.next;
        }
        return null;
    }

  • 0
    D

    :D really the same


Log in to reply
 

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