Last active
May 22, 2016 15:06
Q25ReverseNodes
This file contains hidden or 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* 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