leetcode25. Reverse Nodes in k-Group
class Solution {
public:
ListNode* reverseKGroup(ListNode* head,int k) {
int step = k;
ListNode *front = new ListNode(0);
front->next = head;
ListNode *tail = front;
vector<ListNode*> heads = {};
ListNode *lHead = front;
if(head==NULL){
return NULL;
}
if(k==0 || k==1) return head;
tail = tail->next;
while(tail!=NULL){
front->next= reverseListK(tail,k);
front = tail;
tail = tail->next;
}
return lHead->next;
}
ListNode* reverseListK(ListNode* &head,int k){
if(head==NULL){
return NULL;
}
ListNode *temp = head;
int j = k;
ListNode *h=NULL;
ListNode *cursor = head;
ListNode *tail = head;
while(temp!=NULL&&j>=1){
cursor = temp;
temp = temp->next;
j--;
}
if(j>=1){
h = head;
head = cursor;
return h;
}
cursor = head;
while(k>0 && head!=NULL){
head = head->next;
cursor->next = h;
h = cursor;
cursor = head;
k--;
}
if(k==0) tail->next = cursor;
head = tail;
return h;
}
};