Created
November 18, 2018 03:20
-
-
Save zhangxiaomu01/4983f2d5a67498c0474cbbe1e975d5dc to your computer and use it in GitHub Desktop.
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* reverse(ListNode* head){ | |
ListNode* c_head = NULL; | |
while(head){ | |
ListNode* next = head->next; | |
head->next = c_head; | |
c_head = head; | |
head = next; | |
} | |
return c_head; | |
} | |
ListNode* reverseKGroup(ListNode* head, int k) { | |
ListNode* dummy = new ListNode(0); | |
dummy->next = head; | |
ListNode* tail = dummy; | |
ListNode* sub_head = head; | |
ListNode* toNull = head; | |
while(sub_head){ | |
int i = k-1; | |
while(i>0){ | |
toNull = toNull->next; | |
if(toNull == NULL) | |
return dummy->next; | |
i--; | |
} | |
//Save the next head | |
ListNode* temp = toNull->next; | |
toNull->next = NULL; | |
ListNode* new_sub_head = reverse(sub_head); | |
tail->next = new_sub_head; | |
tail = sub_head; | |
tail->next = temp; | |
sub_head = temp; | |
toNull = temp; | |
} | |
return dummy->next; | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment