https://leetcode.com/problems/intersection-of-two-linked-lists/discuss/
Solution 1.
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
if(!headA || !headB) return nullptr;
ListNode* p = headA, *q = headB;
while(p != q) {
p = p? p->next : headB;
q = q? q->next : headA;
}
return p;
}
Solution 2. Counting the length of the lists.
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
if(!headA || !headB) return nullptr;
ListNode* p, *q;
int na = 0, nb = 0, nd = 0;
p = headA;
while(p) {
na++;
p = p->next;
}
p = headB;
while(p) {
nb++;
p = p->next;
}
if(na>nb) {
p = headA;
q = headB;
}
else {
p = headB;
q = headA;
}
nd = abs(na - nb);
while(nd>0) {
p = p->next;
nd--;
}
while(p != q) {
p = p->next;
q = q->next;
}
return p;
}
No comments:
Post a Comment