Leetcode 160. 相交链表

/**
 * 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 cnt = 0;
        ListNode * tmp =  headA;
        while(tmp)
        {
            cnt++;
            tmp = tmp->next;
        }
        tmp = headB;
        while(tmp)
        {
            cnt--;
            tmp = tmp->next;
        }
        
        ListNode* another = NULL;
        tmp = cnt>0 ?headA:headB;
        another = tmp==headA?headB:headA;
        cnt = cnt>0?cnt:-1*cnt;
        while(cnt)
        {
            tmp=tmp->next;
            cnt--;
        }
        
        while(tmp && another)
        {
            if(tmp == another)
            {
                return tmp;
            }
            tmp=tmp->next;
            another= another->next;
        }
        return NULL;
    }
};

猜你喜欢

转载自www.cnblogs.com/randyniu/p/9462411.html