Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save onelharrison/f54fd5950040976ac261653132d0dfd5 to your computer and use it in GitHub Desktop.
Save onelharrison/f54fd5950040976ac261653132d0dfd5 to your computer and use it in GitHub Desktop.
Increment of a recursive function that reverses a 0-, 1-, and 2-node linked list
def reverse_linked_list_recursive(head):
if head is None: # handles empty linked list
return head
if head.next_node is None: # handles linked list with one node
return head
# A. label the end node as the new head node
new_head = reverse_linked_list_recursive(head.next_node)
# B. set the new head node's next_node to be the previous
# head node (which is now the end node)
head.next_node.next_node = head
# C. set the old head node's next_node to None,
# which makes it the end node
head.next_node = None
return new_head
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment