25. Reverse Nodes in k-Group Posted on 2020-06-19 | Edited on 2021-01-22 | Views: 1 LeetCode Approach: IterationCopy123456789101112131415161718192021222324252627282930313233343536373839/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */class Solution { public ListNode reverseKGroup(ListNode head, int k) { if(head==null||head.next==null||k==1) return head; ListNode dummy=new ListNode(-1),begin=dummy; dummy.next=head; int count=0; while(head!=null){ count++; if(count%k==0){ begin=reverse(begin,head.next); head=begin.next; } else{ head=head.next; } } return dummy.next; } public ListNode reverse(ListNode begin, ListNode end){ ListNode pre=begin, curr=begin.next, start=curr; while(curr!=end){ ListNode next=curr.next; curr.next=pre; pre=curr; curr=next; } begin.next=pre; start.next=curr; return start; }} Approach: RecursionCopy123456789101112131415161718192021222324252627282930313233343536/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode() {} * ListNode(int val) { this.val = val; } * ListNode(int val, ListNode next) { this.val = val; this.next = next; } * } */class Solution { private ListNode reverse(ListNode node,int k){ ListNode newHead=null,ptr=node; while(k>0){ ListNode next=ptr.next; ptr.next=newHead; newHead=ptr; ptr=next; k--; } return newHead; } public ListNode reverseKGroup(ListNode head, int k) { int cnt=0; ListNode ptr=head; while(cnt<k&&ptr!=null){ cnt++;ptr=ptr.next; } if(cnt==k){ ListNode reverseHead=reverse(head,k); head.next=reverseKGroup(ptr,k); return reverseHead; } return head; }}