TGStat
TGStat
Type to search
Advanced channel search
  • flag English
    Site language
    flag Russian flag English flag Uzbek
  • Sign In
  • Catalog
    Channels and groups catalog Regional compilations Thematic compilations Платные каналы Search for channels
    Add a channel/group
  • Ratings
    Rating of channels Rating of groups Posts rating
    Ratings of brands and people
  • Analytics
  • Search by posts
  • Telegram monitoring
  • Promotion
    Advertising through Yandex Business Advertising in channels through TGStat Agency Advertising on TGStat.ru website
C++ Academy

16 Sep, 16:44

Open in Telegram Share Report

💡 Алгоритм Флойда находит цикл в связном списке всего с двумя указателями и `O(1)` дополнительной памяти.

Идея простая:

slow двигается на 1 узел
fast — на 2

Если цикл есть, они обязательно встретятся.

После встречи один указатель возвращаем в head, а дальше оба двигаем по одному узлу. Следующая точка встречи — точное начало цикла.


Node *detect_cycle(Node *head) {
Node *slow = head, *fast = head;

while (fast && fast->next) {
slow = slow->next;
fast = fast->next->next;

if (slow == fast) {
slow = head;

while (slow != fast) {
slow = slow->next;
fast = fast->next;
}

return slow;
}
}

return NULL;
}

Сложность:


O(n) по времени
O(1) по памяти


Один из самых красивых примеров того, как простая математика по модулю превращается в очень практичный алгоритм.

2.1k 0 37 1 15
Catalog
Channels and groups catalog Channels compilations Search for channels Add a channel/group
Ratings
Rating of Telegram channels Rating of Telegram groups Posts rating Ratings of brands and people
API
API statistics Search API of posts API Callback
Our channels
@TGStat @TGStat_Chat @telepulse @TGStatAPI
Read
Академия TGStat Telegram Research 2019 Telegram Research 2021 Telegram Research 2023
Contacts
Справочный центр Support Email Jobs
Miscellaneous
Terms and conditions Privacy policy Public offer
Our bots
@TGStat_Bot @SearcheeBot @TGAlertsBot @tg_analytics_bot @TGStatChatBot