I recently attempted to solve LeetCode problem 141, “Linked List Cycle,” #link of the problem and i figured a solution that worked but left me confused. I’d appreciate some clarification on how this particular solution functions.
Explanation:
I initially considered reversing the linked list to solve the problem, which seemed promising. However, upon closer inspection of the code, I’m puzzled by how head->next
could be NULL if there’s no cycle. Shouldn’t it point to the second node after reversing?
here is my code
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
bool hasCycle(ListNode *head)
{
if(head){
reverseList(head);
if (head->next != NULL)
{
return true;
}
}
return false;
}
void reverseList(ListNode *head)
{
ListNode *temp = head;
ListNode *next = head->next;
head->next = NULL;
while (temp != NULL)
{
temp = next;
if (next != NULL)
{
next = temp->next;
temp->next = head;
head = temp;
}
}
}
};
I know the other solutions but i was just trying all possible solution