Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save onelharrison/33909e19e87c155d19b7deeff951956e to your computer and use it in GitHub Desktop.
Save onelharrison/33909e19e87c155d19b7deeff951956e 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 = head.next_node
# B. set the new head node's next_node to be the previous
# head node, which is to be the end node
new_head.next_node = head
# C. set the old head node's next_node to None,
# which makes the old head node the linked list's 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