C++ easy answer(intersection of Two Linked Lists )


  • 0
    C
    class Solution {
    public:
        ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
            int A_length = length_ListNode(headA);
            int B_length = length_ListNode(headB);
            if(A_length!=B_length)
            {
                if(A_length>B_length)
                {
                    while(A_length!=B_length)
                    {
                        headA = headA->next;
                        A_length--;
                    }
                }
                else{
                    while(A_length!=B_length)
                    {
                        headB = headB->next;
                        B_length--;
                    }
                }
            }
            while(headA!=headB && headA!=NULL)
            {
                headA=headA->next;
                headB = headB->next;
            }
            return headA;
        }
        int length_ListNode(ListNode* head)
        {
            ListNode* temp = head;
            int length=0;
            while(temp){
                length++;
                temp = temp->next;
            }
            return length;
        }
    };

Log in to reply
 

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