LeetCode 面试题 02.07. 链表相交

(面试题 02.07. 链表相交)[https://leetcode-cn.com/problems/intersection-of-two-linked-lists-lcci/]

2 Tag

  1. 链表

3. Code

/**
 * 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=headB, *p2=headA;
        while(p1!=p2)
        {
            if(p1==NULL)
                p1=headB;
            else
                p1=p1->next;
            
            if(p2==NULL)
                p2=headA;
            else
                p2=p2->next;
        }
        return p1;
    }
};

猜你喜欢

转载自www.cnblogs.com/HurryXin/p/12902233.html