-
Notifications
You must be signed in to change notification settings - Fork 0
/
160.intersection-of-two-linked-lists.cpp
57 lines (55 loc) · 1.34 KB
/
160.intersection-of-two-linked-lists.cpp
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
/*
* @lc app=leetcode id=160 lang=cpp
*
* [160] Intersection of Two Linked Lists
*/
// @lc code=start
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
uint32_t GetLinkedListLen(ListNode *head, ListNode *&tail)
{
uint32_t count = 0;
while (head != nullptr) {
count++;
tail = head;
head = head->next;
}
return count;
}
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
ListNode *tailA;
ListNode *tailB;
int m = GetLinkedListLen(headA, tailA);
int n = GetLinkedListLen(headB, tailB);
if (tailA == tailB) {
// Fast Forward
ListNode *visitA = headA;
ListNode *visitB = headB;
while (m > n) {
visitA = visitA->next;
m--;
}
while (n > m) {
visitB = visitB->next;
n--;
}
for (; m >= 0; m--) {
if (visitA == visitB) {
return visitA;
}
visitA = visitA->next;
visitB = visitB->next;
}
}
return nullptr;
}
};
// @lc code=end