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, and only nodes itself is 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
Ideas:
One: This topic can refer to swap nodes in pairs and reverse link list. Use three pointers (pre, Start,then) method to solve, count how many group, the last group does not make any changes.
Two: Recursive method can be used.
Is every k under, recursion once, then k after that next normal walk, K inside call recursive. Notice that the starting initial condition within the recursion is judged so that it returns well.
1 classSolution {2 Public:3ListNode *reversekgroup (ListNode *head,intk)4 {5 6 if(head = = NULL | | head->next = NULL | | k<2)7 returnhead;8 9ListNode * Fakenode =NewListNode (0);TenFakenode-Next =head; OneListNode * p =head; A intLength =0; - while(P) - { thelength++; -p = p->Next; - } - if(k>length) + returnFakenode->Next; -ListNode * pre =Fakenode; +ListNode * start = pre->Next; AListNode * then = startNext; at - intTotal =0; - intCNT =0; - while(then!=NULL) - { - while(cnt!=k-1&&Then ) in { -CNT + +; toStart->next = then->Next; +Then->next = pre->Next; -Pre->next =then ; thethen = start->Next; * } $Total + +;Panax Notoginseng if(Total = = length/k) - Break; thePre =start; +Start = pre->Next; Athen = start->Next; theCNT =0; + } - returnFakenode->Next; $ } $};
Leetcode Reverse Nodes in K-group