Skip to content

Instantly share code, notes, and snippets.

@kanrourou
Created December 25, 2018 19:54
Show Gist options
  • Select an option

  • Save kanrourou/9db4aeeb3470dc6a79af48bde2a2987e to your computer and use it in GitHub Desktop.

Select an option

Save kanrourou/9db4aeeb3470dc6a79af48bde2a2987e to your computer and use it in GitHub Desktop.
/**
* 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) {
ListNode* helper = new ListNode(-1);
helper->next = head;
ListNode* curr = helper;
for(int i = 0; i < m - 1; ++i)
curr = curr->next;
curr->next = reverse(curr->next, n - m);
return helper->next;
}
private:
ListNode* reverse(ListNode* head, int k)
{
ListNode* curr = head->next, *prev = head;
while(curr && k--)
{
ListNode* tmp = curr->next;
curr->next = prev;
prev = curr;
curr = tmp;
}
head->next = curr;
return prev;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment