Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
/**
* 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