Question: Why is this code causing a runtime error for test case: [1,2,3,4,5] /** * Definition for singly-linked list. * struct ListNode { * int val;

Why is this code causing a runtime error for test case: [1,2,3,4,5]

/**

* 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) {

// 1 <= left <= right <= n

if (head == nullptr || left == right) {

return head;

}

ListNode* prev = nullptr;

ListNode* nextNode = nullptr;

ListNode* curr = head;

for(int i = 0; i < left; ++i)

{

curr = curr->next;

}

prev = curr;

for(int i = 0; i < right-left; ++i)

{

nextNode = curr->next;

curr->next = prev;

prev = curr;

curr = nextNode;

}

return head;

}

};

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!