Tuesday, February 22, 2022

LeetCode 160. Intersection of Two Linked Lists

https://leetcode.com/problems/intersection-of-two-linked-lists/
/**
* 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 or !headB) return NULL;
auto pA = headA;
auto pB = headB;
while(pA != pB){
// move both 1 step
pA = pA->next;
pB = pB->next;
// meeth same node
if(pA == pB) break;
// restart different list
if(pA == NULL) pA = headB;
if(pB == NULL) pB = headA;
}
return pA;
}
};

No comments:

Post a Comment