160 Intersection of Two Linked Lists

来源:互联网 发布:java字符串加减乘除 编辑:程序博客网 时间:2024/06/03 17:20
/** * 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) {        ListNode *l1 = headA;        ListNode *l2 = headB;        int count1 = 0;        int count2 = 0;        while(l1)        {            l1 = l1->next;            ++count1;        }        while(l2)        {            l2 = l2->next;            ++count2;        }        l1 = headA;        l2 = headB;        if(count1>count2)        {            for(int i=0;i<count1-count2;++i)                l1 = l1->next;        }        else        {            for(int i=0;i<count2-count1;++i)                l2 = l2->next;        }        while(l1)        {            if(l1==l2)                return l1;            l1 = l1->next;            l2 = l2->next;        }        return NULL;    }};

0 0