Why is my C code running an infinite loop and how do I fix it to obtain my expected output ?
I am supposed to reverse nodes from A to B
So let's say I give an input of :
2 5
1 2 3 4 5 6 7
The first line is to indicate from which index to which index I am supposed to reverse the nodes So here 3 is node A and 6 is node B. The second line is the list I have given. So, I am expecting an output of : 1 2 6 5 4 3 7
This is my code :
ListNode *reverseSegment(ListNode *head, int start, int end)
{
// Write your code here
// Condition to Check if B is valid (if B is valid, then A is valid)
ListNode *temp1 = head;
int count = 0;
while (temp1 != NULL)
{
temp1 = temp1->next;
count++;
}
// Condtion to check if index out of range or invalid
if (count < end)
{
return head;
}
// Declaring Pointers
ListNode *prev = NULL, *cur = head, *next = NULL, *endptr = NULL;
ListNode *temp2 = head;
int diff = end - start;
// Point endptr to the last node of the list
while (temp2->next != NULL)
{
endptr = temp2;
}
// Point next ptr to the node after A
// Point prev pointer to the node after B
//next = cur->next;
prev = endptr;
// Reversing the node from B to A
while ((diff+1) > 0 )
{
next = cur->next;
cur->next = prev;
prev = cur;
cur = next;
diff--;
}
// Point head ptr to node B
head->next = prev;
//return head;
}