Cover image for LeetCode Hot 100 P160 Intersection of Two Linked Lists

LeetCode Hot 100 P160 Intersection of Two Linked Lists


Timeline

Timeline

2026-03-13

init

linked list

Problem:

Align your orbit with hers, and you will meet eventually~

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
/** * Definition for singly-linked list. * struct ListNode { *     int val; *     ListNode *next; *     ListNode(int x) : val(x), next(NULL) {} * }; */#include <cstdlib>struct ListNode {        int val;        ListNode *next;        ListNode(int x)                : val(x)                , next(nullptr)        {        }};class Solution {    public:        ListNode *getIntersectionNode(ListNode *headA, ListNode *headB)        {                int linkA_len = 1, linkB_len = 1, offset;                ListNode *p = headA, *q = headB;                while (p->next != nullptr) {                        p = p->next;                        linkA_len++;                }                while (q->next != nullptr) {                        q = q->next;                        linkB_len++;                }                if (p != q) // Two linked lists that do not intersect                        return nullptr;                offset = std::abs(linkA_len - linkB_len);                p = headA;                q = headB;                if (linkA_len > linkB_len) {                        for (int i = 0; i < offset; i++)                                p = p->next;                } else {                        for (int i = 0; i < offset; i++)                                q = q->next;                }                while (p != q) {                        p = p->next;                        q = q->next;                }                return p;        }};
Loading comments…