Intersection of Two Linked Lists

Write a program to find the node at which the intersection of two singly linked lists begins.

 

For example, the following two linked lists:

A:          a1 → a2
                   ↘
                     c1 → c2 → c3
                   ↗            
B:     b1 → b2 → b3

begin to intersect at node c1.

 

/**
 * 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 Alength = 0;
        int Blength = 0;
        ListNode* ptra = headA;
        ListNode* ptrb = headB;
        
        while(ptra){
            ptra = ptra->next;
            Alength++;
        }
        while(ptrb){
            ptrb = ptrb->next;
            Blength++;
        }
        
        int x = Alength - Blength;
        if(x < 0){
            ptrb = headB;
            ptra = headA;
            for(int i = 0; i < -x; i++){
                ptrb = ptrb->next;
            }
        }
        else{
            ptra = headA;
            ptrb = headB;
            for(int i = 0; i < x; i++){
                ptra = ptra->next;
            }
        }
        
        while(ptra){
            if(ptra == ptrb)
                return ptra;
            ptra = ptra->next;
            ptrb = ptrb->next;
        }
        return ptra;
    }
};

 

posted on 2015-08-30 11:25  horizon.qiang  阅读(125)  评论(0编辑  收藏  举报

导航