joshita / dev

Published

- 2 min read

Reverse linked list in K groups

img of Reverse linked list in K groups

Reverse Nodes in k-Group Given the head of a linked list, reverse the nodes of the list k at a time, and return the modified list. k is a positive integer and is less than or equal to the length of the linked 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 list’s nodes, only nodes themselves may be changed.

TotalValue

   private Node reverseInkGroup (Node head, int k) {
        if(getLen(head) < k) {
            return head;
        }
        int count = 0;
        Node current = head;
        System.out.println("Current here : " + current.val);
        Node prev = null;
        Node next = null;

        while(count < k && current != null) {
            next = current.next;
            current.next = prev;
            prev = current;
            current = next;
            count += 1;
        }
        head.next = reverseInkGroup(current, k);
        //put the current node to the next node of the original node
        //example put 1.next as 4 because by this time the k list has already been reversed
        //example put 4.next as the current node which is 7 (this is how lists are getting joined)
        return prev;
    }
       private int getLen(Node node){
        int count = 0;
        while (node != null) {
            node = node.next;
            count += 1;
        }
       return count;
    }