[leetcode]Intersection of Two Linked Lists

又是个老提

先判断是否相交,如果相交,那么两个链表最后的节点是一样的。

相交那么,我们就来找相交的那个点,假设两个链表一样长,一起往后走,到相同的那个就是交点,不一样长,我们把长的切掉,然后继续这样找就好了。

/**
 * 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) {
        if (headA == nullptr || headB == nullptr) return nullptr;
        int la = 0;
        int lb = 0;
        ListNode* tmpA = headA;
        ListNode* tmpB = headB;
        while(tmpA -> next != nullptr) {
            la++;
            tmpA = tmpA -> next;
        }
        while(tmpB -> next != nullptr) {
            lb++;
            tmpB = tmpB -> next;
        }
        if (tmpA != tmpB) return nullptr;
        tmpA = headA;
        tmpB = headB;
    
        if (lb < la) {
        // la must less than lb
            swap(tmpA, tmpB);
            swap(la, lb);
        }
        int diff = lb - la;
        for (int i = 0; i < diff; i++) {
            tmpB = tmpB -> next;
        }
    
        while (tmpA != tmpB) {
            tmpA = tmpA -> next;
            tmpB = tmpB -> next;
        }
        return tmpA;
    }
};
原文地址:https://www.cnblogs.com/x1957/p/4127492.html