/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ classSolution { public: ListNode* reverseBetween(ListNode* head, int m, int n){ ListNode** s = &head; ListNode *a = nullptr, *b = nullptr; int i = 1; while (i < m - 1) { s = &((*s)->next); i++; } a = *s; b = (*s)->next;
while (i < n) { i++; ListNode *tmp = b; b = b->next; tmp->next = a; a = tmp; }
(*s)->next->next = b; (*s)->next = a;
return head;
} };
This fails for input [5], 1, 1 since we always blindly try to do the reversal operations.
classSolution { public: ListNode* reverseBetween(ListNode* head, int m, int n){ ListNode** s = &head; ListNode *a = nullptr, *b = nullptr; int i = 1; while (i < m - 1) { if (*s) { s = &((*s)->next);
} i++; } a = *s; if (*s) { b = (*s)->next; }
while (i < n) { i++; ListNode *tmp = b; if (b) b = b->next; if (tmp) tmp->next = a; a = tmp; }
// always null check before deref if (*s && (*s)->next) { (*s)->next->next = b; (*s)->next = a; }
return head;
} };
This fails when we have `[3,5], 1, 2`.
We never reverse it.
# Accepted Solution ```cpp /** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ classSolution { public: ListNode* reverseBetween(ListNode* head, int m, int n){ ListNode** s = &head; ListNode *a = nullptr, *b = nullptr; int i = 1; if (m < n) { while (i < m ) { if (*s) { s = &((*s)->next); } i++; } a = *s; if (*s) { b = (*s)->next; }
while (i < n) { i++; ListNode *tmp = b; b = b->next; tmp->next = a; a = tmp; }
// always null check before deref if (*s && (*s)->next) { (*s)->next = b; *s = a; } }