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 −
Let us see the following implementation to get better understanding −
class ListNode: def __init__(self, data, next = None): self.val = data self.next = next def make_list(elements): head = ListNode(elements) for element in elements[1:]: ptr = head while ptr.next: ptr = ptr.next ptr.next = ListNode(element) return head def print_list(head): 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() head = make_list([1,2,3,4,5,6,7,8,9,10]) print_list(ob.solve(head, 3))
[3, 2, 1, 6, 5, 4, 9, 8, 7, 10, ]