leetcode160 C++ 32ms 相交链表

/**
 * 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* pA = headA;
        ListNode* pB = headB;
        int len_a = 0;
        int len_b = 0;
        while(pA != nullptr){
            len_a++;
            pA = pA->next;
        }
        while(pB !=nullptr){
            len_b++;
            pB = pB->next;
        }

        if(len_a >= len_b){
            for(int i=0; i<(len_a-len_b); i++){
                headA = headA->next;
            }
        }
        else{
            for(int i=0;i<(len_b-len_a);i++){
                headB = headB->next;
            }
        }
        
        while(headA != nullptr && headB !=nullptr){
            if(headA == headB){
                return headA;
            }
            else{
                headA = headA->next;
                headB = headB->next;
            }
        }
        
        return nullptr;
        
    }
};
posted @ 2018-07-26 10:36  一条图图犬  阅读(260)  评论(0编辑  收藏  举报