又是个老提

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

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

 

/**
 * 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;
    }
};

 

相关文章:

  • 2021-08-05
  • 2021-12-11
  • 2022-12-23
  • 2022-01-20
  • 2021-10-31
  • 2021-04-20
  • 2021-04-20
猜你喜欢
  • 2021-06-15
  • 2022-02-22
  • 2021-06-07
  • 2021-11-29
  • 2021-12-24
  • 2021-08-16
相关资源
相似解决方案