-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathIntersection_of_Two_Linked_Lists.cpp
More file actions
46 lines (44 loc) · 1.03 KB
/
Intersection_of_Two_Linked_Lists.cpp
File metadata and controls
46 lines (44 loc) · 1.03 KB
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
# number : 160
/**
* 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 == nullptr || headB == nullptr)
return nullptr;
ListNode *pA = headA, *pB = headB;
int countA = 1, countB = 1;
while (pA->next != nullptr) {
countA++;
pA = pA->next;
}
while (pB->next != nullptr) {
countB++;
pB = pB->next;
}
if (pB != pA)
return nullptr;
ListNode *p, *q;
if (countB > countA) {
p = headB;
q = headA;
}
else {
p = headA;
q = headB;
}
for (int i = 0; i < abs(countA - countB); i++)
p = p->next;
while (p != q) {
p = p->next;
q = q->next;
}
return p;
}
};