Created
July 10, 2018 20:27
-
-
Save kalyco/b90b6a6e8f03edf7ee495b5f78f29732 to your computer and use it in GitHub Desktop.
Write an algorithm to detect a cycle in a linked list
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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