s0160
This commit is contained in:
33
src/s0160_intersection_of_two_linked_lists.cpp
Normal file
33
src/s0160_intersection_of_two_linked_lists.cpp
Normal file
@@ -0,0 +1,33 @@
|
||||
#include "s0160_intersection_of_two_linked_lists.hpp"
|
||||
|
||||
ListNode *S0160::getIntersectionNode(ListNode *headA, ListNode *headB) {
|
||||
// 获取两个链表的长度
|
||||
int lenA{0};
|
||||
for (ListNode *ptr = headA; ptr != nullptr; ptr = ptr->next) {
|
||||
++lenA;
|
||||
}
|
||||
int lenB{0};
|
||||
for (ListNode *ptr = headB; ptr != nullptr; ptr = ptr->next) {
|
||||
++lenB;
|
||||
}
|
||||
// 设置两个指针的起始位置
|
||||
ListNode *ptrA = headA, *ptrB = headB;
|
||||
if (lenA > lenB) {
|
||||
for (int i{0}; i < lenA - lenB; ++i) {
|
||||
ptrA = ptrA->next;
|
||||
}
|
||||
} else if (lenA < lenB) {
|
||||
for (int i{0}; i < lenB - lenA; ++i) {
|
||||
ptrB = ptrB->next;
|
||||
}
|
||||
}
|
||||
// 两个指针开始同时往前
|
||||
while (ptrA != nullptr) {
|
||||
if (ptrA == ptrB) {
|
||||
return ptrA;
|
||||
}
|
||||
ptrA = ptrA->next;
|
||||
ptrB = ptrB->next;
|
||||
}
|
||||
return nullptr;
|
||||
}
|
Reference in New Issue
Block a user