[InterviewBit] List Cycle

List Cycle

  • Time :
  • Space :
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
ListNode* Solution::detectCycle(ListNode* A) {
ListNode* slow = A, *fast = A;
while(fast->next and fast->next->next) {
slow = slow->next;
fast = fast->next->next;
if(slow == fast) break;
}
if(fast->next and fast->next->next) {
ListNode* runner = A;
while(runner != slow) {
slow = slow->next;
runner = runner->next;
}
return runner;
}
return NULL;
}

Author: Song Hayoung
Link: https://songhayoung.github.io/2022/09/15/PS/interviewbit/list-cycle/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.