Created
December 25, 2018 20:13
This file contains 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* reverseKGroup(ListNode* head, int k) { | |
if(k <= 1)return head; | |
return reverse(head, k); | |
} | |
private: | |
ListNode* reverse(ListNode* head, int k) | |
{ | |
if(!head)return head; | |
int i = k - 1; | |
ListNode* end = head; | |
while(i-- && end)end = end->next; | |
if(!end)return head; | |
ListNode* curr = head->next, *prev = head; | |
while(prev != end) | |
{ | |
ListNode* tmp = curr->next; | |
curr->next = prev; | |
prev = curr; | |
curr = tmp; | |
} | |
head->next = reverse(curr, k); | |
return prev; | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment