# Program to reverse linked list by groups of size k in Python

PythonServer Side ProgrammingProgramming

Suppose we have a singly linked list, and another value k, we have to reverse every k contiguous group of nodes.

So, if the input is like List = [1,2,3,4,5,6,7,8,9,10], k = 3, then the output will be [3, 2, 1, 6, 5, 4, 9, 8, 7, 10, ]

To solve this, we will follow these steps −

• tmp := a new node with value 0
• next of tmp := node
• prev := null, curr := null
• lp := temp, lc := curr
• cnt := k
• while curr is not null, do
• prev := null
• while cnt > 0 and curr is not null, do
• following := next of curr
• next of curr := prev
• prev := curr, curr := following
• cnt := cnt - 1
• next of lp := prev, next of lc := curr
• lp := lc, lc := curr
• cnt := k
• return next of tmp

Let us see the following implementation to get better understanding −

## Example

class ListNode:
def __init__(self, data, next = None):
self.val = data
self.next = next
def make_list(elements):
for element in elements[1:]:
while ptr.next:
ptr = ptr.next
ptr.next = ListNode(element)
ptr = head print('[', end = "")
while ptr:
print(ptr.val, end = ", ")
ptr = ptr.next
print(']')
class Solution:
def solve(self, node, k):
tmp = ListNode(0)
tmp.next = node
prev, curr = None, node
lp, lc = tmp, curr
cnt = k
while curr:
prev = None
while cnt > 0 and curr:
following = curr.next
curr.next = prev
prev, curr = curr, following
cnt -= 1
lp.next, lc.next = prev, curr
lp, lc = lc, curr
cnt = k
return tmp.next
ob = Solution()
print_list(ob.solve(head, 3))
[1,2,3,4,5,6,7,8,9,10], 3
[3, 2, 1, 6, 5, 4, 9, 8, 7, 10, ]