92. Reverse Linked List II
Difficulty: Medium
Topics: Linked List
Similar Questions:
Problem:
Reverse a linked list from position m to n. Do it in one-pass.
Note: 1 ≤ m ≤ n ≤ length of list.
Example:
Input: 1->2->3->4->5->NULL, m = 2, n = 4 Output: 1->4->3->2->5->NULL
Solutions:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* reverseBetween(ListNode* head, int m, int n) {
if (head == nullptr) return nullptr;
ListNode* dummy = new ListNode(0);
dummy->next = head;
ListNode* cur = dummy;
int index = 0;
while (cur && index < m - 1) {
cur = cur->next;
++index;
}
ListNode* tail = cur;
cur = cur->next;
ListNode* reverseLast = cur;
tail->next = nullptr;
for (int i = 0; i < n - m + 1; ++i) {
ListNode* next = cur->next;
cur->next = tail->next;
tail->next = cur;
cur = next;
}
reverseLast->next = cur;
return dummy->next;
}
};