160. Intersection of Two Linked Lists

Write a program to find the node at which the intersection of two singly linked lists begins.

For example, the following two linked lists:

A:          a1 → a2
                   ↘
                     c1 → c2 → c3
                   ↗            
B:     b1 → b2 → b3

begin to intersect at node c1.

求两个链表的交集。这里应该注意,如果在一个节点两个链表相交了,那么之后的节点也是相交的,所以我们可以这么做:

扫描到链表A或者链表B的末尾时,将A的尾部指针指向B的头,将B的尾部指针指向A的头,知道找到相同的节点

/**
 * 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 *p1 = headA;
        ListNode *p2 = headB;
        bool mark1 = false;
        bool mark2 = false;
        while(p1 != nullptr && p2 != nullptr) {
            if (p1 == p2) return p1;
            p1 = p1->next;
            p2 = p2->next;
            if (p1 == nullptr && !mark1) p1 = headB,mark1 = true;
            if (p2 == nullptr && !mark2) p2 = headA,mark2 = true;
        }
        return nullptr;
    }
};
原文地址:https://www.cnblogs.com/pk28/p/7239186.html