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
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started