【剑指offer】【链表】52.两个链表的第一个公共节点

题目链接:https://leetcode-cn.com/problems/liang-ge-lian-biao-de-di-yi-ge-gong-gong-jie-dian-lcof/

双指针

/**
 * 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 *A = headA, *B = headB;
        while(A != B){
           if(A) A = A -> next;
           else A = headB;

           if(B) B = B -> next;
           else B = headA;
        }
        return A;
    }
};
posted @ 2020-04-02 21:27  NaughtyCoder  阅读(64)  评论(0)    收藏  举报