Skip to content

leet code - 1215 inter section of two linked list

 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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
// 1215
// intersection of two linked list

// easy solution
// starting time
// PM 11:10

// idea - to start at two points simultaneously
// 1. check lengths
// 2. in the short branch, start late

// end time
// PM 11:28
// duration: 18 minutes

#include<stdio.h>

// 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) {
        // check each length
        int cnt1 = 0;
        int cnt2 = 0;
        ListNode *ptrA = headA;
        while(ptrA!=nullptr)
        {
            ptrA = ptrA->next;
            cnt1++;
        }

        ListNode *ptrB = headB;
        while(ptrB!=nullptr)
        {
            ptrB = ptrB->next;
            cnt2++;
        }

        ptrA = headA;
        ptrB = headB;
        printf("%d\n", cnt1);
        printf("%d\n", cnt2);

        if(cnt1 > cnt2)
        {
            int diff = cnt1 - cnt2;
            for(int i=0; i<diff; ++i)
            {
                ptrA = ptrA->next;
            }
            for(int i=0; i<cnt2; ++i)
            {
                if(ptrA == ptrB)
                {
                    return ptrA;
                }
                ptrA = ptrA->next;
                ptrB = ptrB->next;
            }
        }else if(cnt1 < cnt2)
        {
            int diff = cnt2 - cnt1;
            for(int i=0; i<diff; ++i)
            {
                ptrB = ptrB->next;
            }
            for(int i=0; i<cnt1; ++i)
            {
                printf("A: %d\n", ptrA->val);
                printf("B: %d\n", ptrB->val);
                if(ptrA == ptrB)
                {
                    return ptrA;
                }
                ptrA = ptrA->next;
                ptrB = ptrB->next;
            }
        }else
        {
            for(int i=0; i<cnt1; ++i)
            {
                if(ptrA == ptrB)
                {
                    return ptrA;
                }
                ptrA = ptrA->next;
                ptrB = ptrB->next;
            }
        }

        return nullptr;
    }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
//  더 짧은 솔루션
// 두 리스트의 길이를 각각 A, B라고 했을 때, 2A+2B = (A+B) + (A+B)
 class Solution {
 public:
     ListNode *getIntersectionNode(ListNode *headA, ListNode *headB)        {
         ListNode *p1 = headA;
         ListNode *p2 = headB;
         while(p1!=p2){
             p1 = p1 == nullptr?headB:p1->next;
             p2 = p2 == nullptr?headA:p2->next;
         }
         return p1;
     }
 };