We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
In a linear linked list, each node from 1st to last reserves addresses in ascending order. For example, the 1st node's address will be less than the second node. Similarly, the second node's address will be less than the 3rd node. Therefore I'm checking if the 1st node's address is greater than the second node and have continued checking until we reach NULL. If the next node's address is less than the current node and next node is not NULL then next node must be pointing to a previous node somewhere. That means the list has a cycle. And if the next node is less than the current node and the next node is NULL than we confirm that the control has reached the last node and it doesn't have any cycle.
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Linked Lists: Detect a Cycle
You are viewing a single comment's thread. Return to all comments →
In a linear linked list, each node from 1st to last reserves addresses in ascending order. For example, the 1st node's address will be less than the second node. Similarly, the second node's address will be less than the 3rd node. Therefore I'm checking if the 1st node's address is greater than the second node and have continued checking until we reach NULL. If the next node's address is less than the current node and next node is not NULL then next node must be pointing to a previous node somewhere. That means the list has a cycle. And if the next node is less than the current node and the next node is NULL than we confirm that the control has reached the last node and it doesn't have any cycle.