Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class ListNode:
- def __init__(self, value=0, next=None):
- self.value = value
- self.next = next
- def reverse_linked_list(head, k):
- current = head
- prev = None
- next_node = None
- count = 0
- # Count the number of nodes in the current group
- temp = head
- while temp is not None and count < k:
- temp = temp.next
- count += 1
- # If the number of nodes in the group is less than k, no need to reverse
- if count < k:
- return head
- # Reverse the nodes in the current group
- while count > 0:
- next_node = current.next
- current.next = prev
- prev = current
- current = next_node
- count -= 1
- # Recursively reverse the rest of the linked list
- if next_node is not None:
- head.next = reverse_linked_list(next_node, k)
- return prev
- def print_linked_list(head):
- current = head
- while current is not None:
- print(current.value, end=" -> ")
- current = current.next
- print("None")
- # Example usage:
- # Create a linked list: 1 -> 2 -> 3 -> 4 -> 5
- head = ListNode(1, ListNode(2, ListNode(3, ListNode(4, ListNode(5)))))
- # Reverse in groups of k = 3
- new_head = reverse_linked_list(head, 3)
- # Print the reversed linked list
- print_linked_list(new_head)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement