I’m trying to reverse a segment of a singly linked list in C++ using the following function. However, I’m seeing unexpected behavior when the value of left
is 2. Specifically, the first while
loop executes even though the condition should evaluate to false
.
Here is my code:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* reverseBetween(ListNode* head, int left, int right) {
ListNode* l = head, *r = head;
while (left - 2 != 0) {
cout << left << endl;
l = l->next;
left--;
}
while (right) {
r = r->next;
right--;
}
ListNode* p = nullptr, *q = l->next;
while (q != r) {
ListNode* tmp = q->next;
q->next = p;
p = q;
q = tmp;
}
l->next->next = q;
l->next = p;
return head;
}
};
Input:
head = [1,2,3,5,5]
left = 2
right = 4
Stdout:
1
0
There's only one cout statement i.e in the first while loop but for this input it should never go inside. I can try other ways and I know other solutions to this problem I only want to know why is it showing this abnormal behaviour.