-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathreverse_nodes_in_k_groups.py
64 lines (56 loc) · 1.69 KB
/
reverse_nodes_in_k_groups.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
'''
Reverse nodes in k groups - CodeSignal
Given a linked list and an integer K, the task is to reverse every K nodes of the given linked list.
'''
# Singly-linked lists are already defined with this interface:
class ListNode(object):
def __init__(self, x, next=None):
self.value = x
self.next = next
def reverseNodesInKGroups(l, k):
if k <= 1 or not l or not l.next:
return l
prev = None
curr = l
temp = None
tail = None
newHead = None
join = None
count = 0
# Traverse till the end of the linked list
while (curr) :
count = k
join = curr
prev = None
it = curr
while it and count:
count = count - 1
it = it.next
if count != 0 and tail:
tail.next = curr
break
# Reverse group of k nodes of the linked list
for i in range(k):
temp = curr.next
curr.next = prev
prev = curr
curr = temp
# Sets the new head of the input list
if (newHead == None):
newHead = prev
# Tail pointer keeps track of the last node
# of the k-reversed linked list. We join the
# tail poer with the head of the next
# k-reversed linked list's head
if (tail != None):
tail.next = prev
# The tail is then updated to the last node
# of the next k-reverse linked list
tail = join
# newHead is new head of the input list */
return newHead
# Test
l = ListNode(1, ListNode(2, ListNode(3, ListNode(4, ListNode(5)))))
print l
k = 2
print reverseNodesInKGroups(l,k)