Last active
April 19, 2020 17:30
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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