Reverse a Linked List in groups of a given size
Data Structures and Algorithms Note
Published in
2 min readJan 21, 2022
how I would do
For the purpose of reverse linked list, think about using stack first!
class Node:
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def push(self, new_data):
new_node = Node(new_data)
new_node.next = self.head
self.head = new_node
def printList(self):
temp = self.head
while temp:
print(temp.data)
temp = temp.next def reverse(self, head, k):
if head is None:
return
curr = head
prev = None
new_stack = []
while curr is not None:
count = 0
# exit for loop when current is None or count >= k
while curr is not None and count < k:
new_stack.append(curr)
curr = curr.next
count += 1
# pop element of stack one by one until stack is empty
while new_stack:
# head node
if prev is None:
self.head = prev = new_stack.pop()
else:
prev.next = new_stack.pop()
prev = prev.next
# next of last element will point to None.
prev.next = None
curr will stop at the first node of the next round until it reached the last node.next, which is None.
the element stored in the stack will be popped and linked as a set, when the stack is empty, continue the process for the next round.
when the second last.next = new_stack.pop(), which means the new_stack become empty, and prev are assign as the last Node.
when curr is None, stop the while loop and at the end, make the next of prev, which is the last Node point to None to end the linked list.