Cover image for Interview Classic 150 Questions P141 Linked List Cycle

Interview Classic 150 Questions P141 Linked List Cycle


Timeline

Timeline

2025-11-19

init

Linked list, two pointers

Problem:

Two pointers, fast and slow pointers

1234567891011121314151617181920212223242526272829303132333435
struct ListNode {	int val;	ListNode *next;	ListNode(int x)		: val(x)		, next(nullptr)	{	}};class Solution {    public:	bool hasCycle(ListNode *head)	{		ListNode *low = head, *fast = head;		do {			if (low == nullptr || low->next == nullptr)				return false;			else				low = low->next;			if (fast == nullptr || fast->next == nullptr || fast->next->next == nullptr)				return false;			else				fast = fast->next->next;		} while (low != fast);		if (low != nullptr)			return true;		return false;	}};
Loading comments…