[AlgoExpert] Find Loop

Find Loop

  • Time : O(n)
  • Space : O(1)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <vector>
using namespace std;

class LinkedList {
public:
int value;
LinkedList *next;

LinkedList(int value);
};

LinkedList *findLoop(LinkedList *head) {
LinkedList *slow = head, *fast = head;
do {
slow = slow->next;
fast = fast->next->next;
}while(slow != fast);

while(head != slow) {
slow = slow->next;
head = head->next;
}
return head;
}
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/05/10/PS/AlgoExpert/find-loop/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.