Skip to content

Instantly share code, notes, and snippets.

@xzhang311
Last active May 22, 2016 15:06
Q25ReverseNodes
/**
* 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(head==NULL||k==1) return head;
ListNode* p0=head;
ListNode* p1=head;
int steps=1;
while(steps!=k&&p1!=NULL){
p1=p1->next;
steps++;
}
if(steps!=k||p1==NULL)
return head;
ListNode* nextHead=p1->next;
ListNode* p01=p0->next;
ListNode* p011;
while(p0!=p1){
p011=p01->next;
p01->next=p0;
p0=p01;
p01=p011;
}
head->next=reverseKGroup(nextHead, k);
return p1;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment