Advertisement
naren_paste

Reverse_Linked_list

Jan 19th, 2024
786
1
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.30 KB | Source Code | 1 0
  1. class ListNode:
  2.     def __init__(self, value=0, next=None):
  3.         self.value = value
  4.         self.next = next
  5.  
  6. def reverse_linked_list(head, k):
  7.     current = head
  8.     prev = None
  9.     next_node = None
  10.     count = 0
  11.  
  12.     # Count the number of nodes in the current group
  13.     temp = head
  14.     while temp is not None and count < k:
  15.         temp = temp.next
  16.         count += 1
  17.  
  18.     # If the number of nodes in the group is less than k, no need to reverse
  19.     if count < k:
  20.         return head
  21.  
  22.     # Reverse the nodes in the current group
  23.     while count > 0:
  24.         next_node = current.next
  25.         current.next = prev
  26.         prev = current
  27.         current = next_node
  28.         count -= 1
  29.  
  30.     # Recursively reverse the rest of the linked list
  31.     if next_node is not None:
  32.         head.next = reverse_linked_list(next_node, k)
  33.  
  34.     return prev
  35.  
  36. def print_linked_list(head):
  37.     current = head
  38.     while current is not None:
  39.         print(current.value, end=" -> ")
  40.         current = current.next
  41.     print("None")
  42.  
  43. # Example usage:
  44. # Create a linked list: 1 -> 2 -> 3 -> 4 -> 5
  45. head = ListNode(1, ListNode(2, ListNode(3, ListNode(4, ListNode(5)))))
  46.  
  47. # Reverse in groups of k = 3
  48. new_head = reverse_linked_list(head, 3)
  49.  
  50. # Print the reversed linked list
  51. print_linked_list(new_head)
  52.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement