Skip to content

Instantly share code, notes, and snippets.

@kalyco
Created July 10, 2018 20:27
Show Gist options
  • Save kalyco/b90b6a6e8f03edf7ee495b5f78f29732 to your computer and use it in GitHub Desktop.
Save kalyco/b90b6a6e8f03edf7ee495b5f78f29732 to your computer and use it in GitHub Desktop.
Write an algorithm to detect a cycle in a linked list
// Assume a linked list object with mHead, and mTail LLNodes, and mSize for size of list
// If there is a cycle, the linked list would never break out of a while loop.
// So if it exceeds the length of the list, we know there's a cycle somewhere
bool isCycle() {
if(mHead == NULL) return false;
node * n = mHead;
int lSize = mSize;
while(true) {
if (n->next == NULL) return false;
if(lSize == -1) return true;
lSize--;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment