Problem:
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,Given this linked list: 1->2->3->4->5
For k = 2, you should return: 2->1->4->3->5
For k = 3, you should return: 3->2->1->4->5
Analysis:
Solutions:
C++:
void rebuild(ListNode **Start, ListNode **End)
{
ListNode *tempEnd=(*End)->next;
ListNode *pCur=*Start, *pUpperNode=*Start;
while(pCur!=tempEnd){
ListNode *tempNext=pCur->next;
if(pCur==*Start){
pCur->next=tempEnd;
*End=pCur;
}else{
pCur->next=pUpperNode;
}
pUpperNode=pCur;
pCur=tempNext;
}
*Start=pUpperNode;
}
ListNode *reverseKGroup(ListNode *head, int k)
{
/*
* Move k steps from the the last node. (The head and the tail should be computed seperatedly.)
* Cut a sub linked list of lastnode->next and lastnode->next + k.
* Reverse and then recover.
*/
if(head==NULL || head->next==NULL || k<=1) return head;
ListNode *pCur=head;
ListNode *pStartPrev=head, *pEnd=head;
while(pCur!=NULL){
for(int i=0; i<k-1; ++i){
pCur=pCur->next;
if(pCur==NULL)
return head;
}
pEnd=pCur;
pCur=pCur->next;
if(pStartPrev==head){
rebuild(&head, &pEnd);
}else{
rebuild(&(pStartPrev->next), &pEnd);
}
pStartPrev=pEnd;
}
return head;
}
Java
:
Python: