Files
  • main.py
main.py
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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
class LN:
    def __init__(self, val, next=None):
        self.value = val
        self.next = next


def arr_to_ll(arr, i=0):
    if not arr:
        return None
    if i == len(arr) - 1:
        return LN(arr[i])
    return LN(arr[i], arr_to_ll(arr, i+1))


def reverse_ll_recursive(ll):
    if not ll or not ll.next:
        return ll
    first = ll
    second = ll.next
    first.next = None
    head = reverse_ll_recursive(second)
    second.next = first
    return head

def check_nodes(ll, k):
    while ll and k:
        ll = ll.next
        k -= 1
    return k == 0

def reverse_ll_iterative(ll, k, new_head=None):
    if not jump_to_next(ll, k):
        return ll
    while k:
        temp = ll
        ll = ll.next
        temp.next = new_head
        new_head = temp
        k -= 1
    return new_head

def jump_to_next(ll, k):
    while ll and k:
        ll = ll.next
        k -= 1
    return ll


def print_ll(ll):
    print()
    while ll:
        print(ll.value, end='->')
        ll = ll.next

def jump_to_end(ll):
    while ll.next:
        print(ll.value)
        ll = ll.next
    return ll

def reverse_k_groups(ll, k):
    head = reverse_ll_iterative(ll, k)
    while head.next:
        print(head.value)
        head = head.next
    print(head)
    print("DONE")
    current_end = jump_to_end(head)
    while ll:
        nxt = jump_to_next(ll, k)
        current_end.next = reverse_ll_iterative(ll, k)
        current_end = jump_to_end(current_end)
        ll = nxt
        print(ll.value)
    return head
        
        


arr = [1, 2, 3, 4, 5]
ll = arr_to_ll(arr)

head = reverse_k_groups(ll, 2)

print_ll(head)