为什么我的 C 代码运行无限循环,如何修复它以获得预期的输出?
我应该将节点从 A 反转到 B
所以假设我输入:
2 5
1 2 3 4 5 6 7
第一行是指示我应该从哪个索引到哪个索引来反转节点所以这里3是节点A,6是节点B。第二行是我给出的列表。所以,我期待输出:1 2 6 5 4 3 7
这是我的代码:
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;
}