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

 

上一篇:记录一个攻防世界的题目!!!


下一篇:LeetCode 160 相交链表