Created
July 8, 2020 12:02
-
-
Save Kristian-Roopnarine/e6851b063f4d4b6c550bca3a0d238d28 to your computer and use it in GitHub Desktop.
Code to reverse a singly linked list
This file contains 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
class Solution: | |
def reverseList(self, head: ListNode) -> ListNode: | |
# check if head exists or if there are at least 2 nodes. | |
if head is None or head.next is None: | |
return head | |
else: | |
current_node = head | |
while current_node.next is not None: | |
# get next node | |
next_node = current_node.next | |
# move current_node forward | |
current_node.next = next_node.next | |
# push next_node to front of linked list | |
next_node.next = head | |
# reassign head | |
head = next_node | |
return head |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment