How to detect loops on a single linked list?
Anonymous
Use two pointers to the elements in the list. They both move forward in the linked list. The first one moves one unit at a time while the second one moves two times (1 2 2 1 2 2 1 2 2 1 2 2 etc). If they ever collide after incrementing the value (point to the same element), then the list has cycles. If the fastest one reaches the end of the list, then the list doesn't have cycles. Big O: O(n)
Check out your Company Bowl for anonymous work chats.
Copyright © 2008-2026. Indeed, Inc. "Glassdoor," "Worklife Pro," "Bowls," and logo are proprietary trademarks of Indeed, Inc.