Posts Reverse a Linked List in Groups (geeksforgeeks - SDE Sheet)
Post
Cancel

Reverse a Linked List in Groups (geeksforgeeks - SDE Sheet)

PROBLEM DESCRIPTION

Given a linked list, the task is to reverse every k node (where k is an input to the function) in the linked list. If the number of nodes is not a multiple of k then left-out nodes, in the end, should be considered as a group and must be reversed (See Example 2 for clarification).

geeksforgeeks

SOLUTION

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
class Solution {

    public static Node reverse(Node node, int k) {

        if(node == null)
            return null;

        int count = 0;

        Node p1 = node;

        for(int i=0; i<k-1; i++){

            if(p1 == null)
                break;

            count++;
            p1 = p1.next;

        }

        // last set of nodes
        if(p1 == null)
            return reverseLinkedList(node);

        Node p2 = p1.next;
        p1.next = null;

        Node newHead = reverseLinkedList(node);

        node.next = reverse(p2, k);

        return newHead;

    }

    public static Node reverseLinkedList(Node head){
        Node h1 = head;
        Node h2 = null;

        while(h1 != null){
            Node t = h1;
            h1 = h1.next;
            t.next = h2;
            h2 = t;
        }
        return h2;
    }

}
This post is licensed under CC BY 4.0 by the author.