160. 相交链表

题目链接

解题思路:双指针

C++:

/**
 * 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 || !headB) {
            return NULL;
        }
        if (headA == headB) {
            return headA;
        }

        ListNode *you = headA, *she = headB;
        while (you != she) {
            you = you ? you->next : headB;
            she = she ? she->next : headA;
        }
        return you;
    }
};

 

posted @ 2021-04-03 20:38  洗盏更酌  Views(18)  Comments(0Edit  收藏  举报