Created
January 18, 2014 03:47
-
-
Save safeng/8485913 to your computer and use it in GitHub Desktop.
Reverse Nodes in k-Group
Given a linked list, reverse the nodes of a linked list k at a time and return its modified list. If the number of nodes is not a multiple of k then left-out nodes in the end should remain as it is. You may not alter the values in the nodes, only nodes itself may be changed. Only constant memory is allowed. For example,
…
This file contains 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 * reverseList(ListNode * head, ListNode * end) // reverse list from [head, end) | |
{ | |
if(head->next == end) | |
return head; | |
else | |
{ | |
ListNode * newHead = reverseList(head->next, end); | |
head->next->next = head; | |
head->next = end; | |
return newHead; | |
} | |
} | |
ListNode *reverseKGroup(ListNode *head, int k) { | |
// IMPORTANT: Please reset any member data you declared, as | |
// the same Solution instance will be reused for each test case. | |
if(head == NULL) | |
return NULL; | |
if(k == 1) | |
return head; | |
ListNode guard(0); | |
guard.next = head; | |
ListNode * p = &guard; | |
ListNode * pp = &guard; | |
while(1) | |
{ | |
for(int i = 0; i<k; ++i) | |
{ | |
pp = pp->next; | |
if(pp == NULL) | |
return guard.next; | |
} | |
pp = pp->next; | |
// from p->next, pp | |
ListNode * start = p->next; | |
p->next = reverseList(p->next, pp); | |
p = start; | |
pp = start; | |
} | |
return guard.next; | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment