From 4099f80edb0c98396ea234a46aa630ffc56a63bc Mon Sep 17 00:00:00 2001 From: Sainnhe Park Date: Fri, 2 Dec 2022 17:24:26 +0800 Subject: [PATCH] s0160 --- ...s0160_intersection_of_two_linked_lists.hpp | 15 +++++++++ notes/src/linked-list.md | 21 ++++++++++++ ...s0160_intersection_of_two_linked_lists.cpp | 33 +++++++++++++++++++ 3 files changed, 69 insertions(+) create mode 100644 include/s0160_intersection_of_two_linked_lists.hpp create mode 100644 src/s0160_intersection_of_two_linked_lists.cpp diff --git a/include/s0160_intersection_of_two_linked_lists.hpp b/include/s0160_intersection_of_two_linked_lists.hpp new file mode 100644 index 0000000..3ce45b1 --- /dev/null +++ b/include/s0160_intersection_of_two_linked_lists.hpp @@ -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 diff --git a/notes/src/linked-list.md b/notes/src/linked-list.md index c2c503e..7f66395 100644 --- a/notes/src/linked-list.md +++ b/notes/src/linked-list.md @@ -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 。 diff --git a/src/s0160_intersection_of_two_linked_lists.cpp b/src/s0160_intersection_of_two_linked_lists.cpp new file mode 100644 index 0000000..e045db0 --- /dev/null +++ b/src/s0160_intersection_of_two_linked_lists.cpp @@ -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; +}