I have learned recently that:
(typically)heap in memory always grows upward
refer to-> https://unix.stackexchange.com/questions/466443/do-memory-mapping-segment-and-heap-grow-until-they-meet-each-other
I didn't understand most of it but when I searched for whether heap grows upwards in memory then I got similar results.
Considering the above fact in c/c++, I have written a function checking for cycle detection where if the traversing pointer to structure temp
points to a memory address less than the memory address of previous node in the linked list then the function returns TRUE for cycle detection.
Unfortunately the below code is not giving desired results on hackerrank and I want to know why. The code is:
bool has_cycle(SinglyLinkedListNode* head) {
struct SinglyLinkedListNode* temp = head;
int x;
if( temp == NULL )
return false; //FALSE indicates No cycle detected in linked list
if( temp->next == NULL )
return false;
x = temp;
while( temp->next != NULL )
{
temp = temp->next;
if( x >= temp )
return true; //TRUE indicates Cycle detected in linked list
x= temp;
}
return false;
}
I have checked for the condition if the memory allocation in heap is downwards if( x <= temp )
(descending order) as memory allocation is device/compiler specific but that too didn't work.
I want to know as to why this code is not working and what conceptual errors this code posseses.