Created
December 25, 2018 19:54
-
-
Save kanrourou/9db4aeeb3470dc6a79af48bde2a2987e to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /** | |
| * 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