-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathig_0207.cpp
More file actions
57 lines (52 loc) · 1.07 KB
/
ig_0207.cpp
File metadata and controls
57 lines (52 loc) · 1.07 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
47
48
49
50
51
52
53
54
55
56
57
/**
* @file ig_0207.cpp
* @brief https://leetcode-cn.com/problems/intersection-of-two-linked-lists-lcci/
* @author YongDu
* @date 2021-09-08
*/
/**
* 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 (nullptr == headA || nullptr == headB) {
return nullptr;
}
int lenA = 0;
int lenB = 0;
ListNode *curA = headA;
ListNode *curB = headB;
while (curA) {
lenA++;
curA = curA->next;
}
while (curB) {
lenB++;
curB = curB->next;
}
curA = headA; // 记得重置结点
curB = headB;
if (lenB > lenA) {
std::swap(lenA, lenB);
std::swap(curA, curB);
}
int gap = lenA - lenB;
while (gap--) {
curA = curA->next;
}
while (curA) {
if (curA == curB) {
return curA;
}
curA = curA->next;
curB = curB->next;
}
return nullptr;
}
};