class Node:
    def __init__(self, value, next = None):
        self.value = value
        self.next = next

    def print_list(self):
        curr = self
        s = ""
        while curr is not None:
            if curr.next is not None:
                s += str(curr.value) + "->"
            else:
                s += str(curr.value)
            curr = curr.next
        print(s)
        return s

def reverse_every_k_elements(head, k):
    if head is None or k <= 1:
        return head
    previous, current = None, head
    while True:
        i = 0
        last_node_of_previous_part = previous
        last_node_of_sublist = current
        while current is not None and i < k:
            next = current.next
            current.next = previous
            previous = current
            current = next
            i += 1
        if last_node_of_previous_part is not None:
            last_node_of_previous_part.next = previous
        else:
            head = previous
        last_node_of_sublist.next = current
        if current is None:
            break
        previous = last_node_of_sublist
    return head 


def main():
    head = Node(1)
    head.next = Node(2)
    head.next.next = Node(3)
    head.next.next.next = Node(4)
    head.next.next.next.next = Node(5)
    head.next.next.next.next.next = Node(6)
    head.next.next.next.next.next.next = Node(7)
    head.next.next.next.next.next.next.next = Node(8)

    print("Nodes of original LinkedList are: ", end='')
    head.print_list()
    result = reverse_every_k_elements(head, 3)
    print("Nodes of reversed LinkedList are: ", end='')
    result.print_list()


main()

