s0160
This commit is contained in:
parent
88ec5dc3d8
commit
4099f80edb
15
include/s0160_intersection_of_two_linked_lists.hpp
Normal file
15
include/s0160_intersection_of_two_linked_lists.hpp
Normal file
@ -0,0 +1,15 @@
|
||||
#ifndef S0160_INTERSECTION_OF_TWO_LINKED_LISTS_HPP
|
||||
#define S0160_INTERSECTION_OF_TWO_LINKED_LISTS_HPP
|
||||
|
||||
struct ListNode {
|
||||
int val;
|
||||
ListNode *next;
|
||||
ListNode(int x) : val(x), next(nullptr) {}
|
||||
};
|
||||
|
||||
class S0160 {
|
||||
public:
|
||||
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB);
|
||||
};
|
||||
|
||||
#endif
|
@ -1 +1,22 @@
|
||||
# 总结
|
||||
|
||||
首先考虑递归 (e.g. s0206, s0024)
|
||||
|
||||
其次考虑双指针 (e.g. s0206, s0019, s0160)
|
||||
|
||||
递归遍历单链表:
|
||||
|
||||
```cpp
|
||||
void iter(ListNode *node) {
|
||||
if (node == nullptr) {
|
||||
return;
|
||||
}
|
||||
/*
|
||||
your
|
||||
condition
|
||||
*/
|
||||
iter(node->next);
|
||||
}
|
||||
```
|
||||
|
||||
递归遍历的意义在于让回溯单链表,也就是先遍历到结尾,然后从后往前遍历到某个 condition 。
|
||||
|
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;
|
||||
}
|
Loading…
Reference in New Issue
Block a user