1 Topics:
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
2 Ideas:
I figured it out for myself. Using recursion, only K is processed at a time, and the remainder is processed recursively.
3 Code:
PublicListNode Reversekgroup (ListNode head,intk) {if(Head = =NULL){ return NULL; } ListNode fake=NewListNode (0); Fake.next=Head; ListNode l=Head; intCount = 0; while(L! =NULL) {Count++; L=L.next; } if(K>count)returnHead; ListNode After=NULL; L=Head; ListNode Pre=L.next; for(inti=0; i<k; i++) {Fake.next=l; L.next=After ; after=l; L=Pre; if(Pre! =NULL) Pre =Pre.next; } Head.next=Reversekgroup (l,k); returnFake.next; }
[Leetcode 25] Reverse Nodes in K-group