Reverse Linked List in Groups of Given Size

This class discusses Reverse Linked List in Groups of a Given Size.

Readers can easily take a competitive coding course to crack product development companies. Click here.

The reader should have basic coding skills to solve competitive coding.

Take the course placement training for service-based companies for basic coding. Click Here.

Question:

Given a linked list of size N.

Our task is to reverse the linked list in groups of size K.

If the number of nodes, in the end, is less than K, then consider it as a group and reverse.

Example:

Input: 1-2-3-4-5-6-7-8-None

K = 3

Output: 3-2-1-6-5-4-8-7-None

It is our first example of a linked list, so we refreshed the linked list concept.

The reader should have a memory visualisation of how linked lists allocate memory.

Writing logic is easy if the reader has the memory visualisation.

Use a loop to move from one node to another until we find None.

We discussed the logic of reversing a linked list in our basic course.

We use the same logic with bit changes to reverse in groups.

The above video explains the Complete logic.

Code:

class Node:

    def __init__(self, data):

        self.data = data

        self.next = None

class Solution:

    def reverse(self,head, k):

        prev=None

        i=0

        curr=head

        while curr!=None and i<k:

            tmp=curr.next

            curr.next=prev

            prev=curr

            curr=tmp

            i+=1

        i=0

        if tmp!=None:

            head.next=self.reverse(tmp,k)

        head=prev

        return head 

n=int(input(“enter number of nodes”))

k=int(input(“enter k value”))

head=None

for i in range(n):

    x=int(input(“enter data”))

    ob=Node(x)

    if(i==0):

        head=ob

    else:

        tmp=head

        while(tmp.next!=None):

            tmp=tmp.next

        tmp.next=ob

ob1=Solution()

z=ob1.reverse(head,k)

tmp=z

while(tmp.next!=None):

    print(tmp.data)

    tmp=tmp.next

print(tmp.data)