Website Summary Files Commits Branches @commit @diff @stats
path: root / Practicum / pract05 / solutions / Task04.cpp
blob: 3fc11a5de276151f8ce891a8a90774b1c9681861 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    size_t getLen(ListNode* head)
    {
        size_t cnt = 0;
        while(head)
        {
            head = head->next;
            cnt++;
        }

        return cnt;
    }
    ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
        if(!headA || !headB)
            return nullptr;

        size_t sizeA = getLen(headA);
        size_t sizeB = getLen(headB);

        while(sizeA > sizeB)
        {
            headA = headA->next;
            sizeA--;
        }

        while(sizeB > sizeA)
        {
            headB = headB->next;
            sizeB--;
        }

        while(headA && headB)
        {
            if(headA == headB)
                return headA;

            headA = headA->next;
            headB = headB->next;
        }
        
        return nullptr;
    }
};