LeetCode101: 142. Linked List Cycle II

tags: Cycle detection,Fast & Slow Pointers,LeetCode101 /** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode *detectCycle(ListNode *head) { if (head == nullptr || head->next == nullptr) { return nullptr; } // tortoise move 1 step auto slow = head->next; // hare move 2 steps auto fast = head->next->next; while (slow != fast) { if (slow == nullptr || fast == nullptr || fast->next == nullptr) { return nullptr; } slow = slow->next; fast = fast->next->next; } slow = head; while (slow != fast) { slow = slow->next; fast = fast->next; } return slow; } };

March 29, 2022 · 1 min · Gray King

Fast & Slow Pointers

tags: Algorithm,Two Pointers

March 29, 2022 · 1 min · Gray King

Cycle detection

tags: Algorithm,Linked List,Fast & Slow Pointers source: https://en.wikipedia.org/wiki/Cycle%5Fdetection Floyd’s tortoise and hare With two pointers: tortoise move slow: move 1 step in each loop. hare move fast: move 2 steps in each loop. If there is a circle existed, tortoise and hare will meet eventually in the circle. Now both tortoise and hare are in the circle, how to figure out the beginning of the circle? We put tortoise back to the beginning they both started. Such as, the first element of the linked list. Then we move both tortoise and hare step by step, they will meet in the beginning of the circle.

March 29, 2022 · 1 min · Gray King

Tree

tags: Data Structures

March 29, 2022 · 1 min · Gray King

Binary Tree

tags: Tree

March 29, 2022 · 1 min · Gray King