Skip to content

Instantly share code, notes, and snippets.

@zhangxiaomu01
Created November 18, 2018 03:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zhangxiaomu01/4983f2d5a67498c0474cbbe1e975d5dc to your computer and use it in GitHub Desktop.
Save zhangxiaomu01/4983f2d5a67498c0474cbbe1e975d5dc 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* 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