Problem Statement

Pattern:


Simliar to Reverse LinkedList in Groups of K except If the number of nodes is not a multiple of k then left-out nodes, in the end, should remain as it is.

this is the iterative version

Solution

public ListNode reverse (ListNode curr, ListNode prev, int k) {
	while(k-- > 0) {
		ListNode next = curr.next;
		curr.next = prev;
		prev = curr;
		curr = next;
	}
	return prev;
}
 
public ListNode reverseKGroup (ListNode head, int k){
	ListNode dummy = new ListNode(-1, head), dummyHead = dummy, successor = dummy.next;
 
	while(successor != null) {
		int count = k;
		// check if k-reversible
		while(count > 0 && successor != null) {
			successor = successor.next;
			count--;
		}
		if(successor == null && count > 0) break;
		
		dummy.next = reverse(dummy.next, successor, k);
		while(count++ < k && dummy != null) dummy = dummy.next;
	}
 
	return dummyHead.next;
}

Notes