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
Analysis:
Linked list operation, itself does not have any tall on the algorithm or data structure. But there are so many small details that are easy to get a big head, and few people can write about it at once. Even more hateful is, even if finished, every other day in looking at their own before the idea of writing, still have to cost a lot of brain cells to clarify .....
The idea of this problem is to first calculate the length of the linked list Len, then Len divided by K to get the total we need to reverse several sub-linked lists. It is not difficult to reverse the operation of a linked list, but it is difficult to connect the two sub-linked lists. You have to record the tail and head of this sub-list and set the nodes they point to at the right time ... In short, it is difficult to describe the text clearly, directly on the code bar. Just a few lines of code took two hours to fix.
1 /**2 * Definition for singly-linked list.3 * public class ListNode {4 * int val;5 * ListNode Next;6 * ListNode (int x) {7 * val = x;8 * next = null;9 * }Ten * } One */ A Public classSolution { - PublicListNode Reversekgroup (ListNode head,intk) { - intLen = 0; theListNode HEADBP =head; - while(HEADBP! =NULL){ -len++; -HEADBP =Headbp.next; + } - if(Len < 2) {returnhead;} + A intReversetimes = (len/k); at -ListNode Myhead =NewListNode (0); -Myhead.next =head; -ListNode Curr =Myhead; -ListNode next =head; -ListNode prev =NULL; inListNode Rhead =Curr; -ListNode Rtail =Curr.next; to + for(intj=0;j<reversetimes;j++){ -Rhead =Curr; theRtail =Curr.next; *Curr =Curr.next; $Next =Curr;Panax Notoginseng for(inti = 0; I < K; i++) { -Next =Next.next; theCurr.next =prev; +Prev =Curr; ACurr =Next; the } +Rhead.next =prev; -Rtail.next =Next; $Prev =NULL; $Curr =Rtail; - } - returnMyhead.next; the } -}
[Leetcode] Algorithm topic-Reverse Nodes in K-group