Skip to content

Instantly share code, notes, and snippets.

@Kristian-Roopnarine
Created July 8, 2020 12:02
Show Gist options
  • Save Kristian-Roopnarine/e6851b063f4d4b6c550bca3a0d238d28 to your computer and use it in GitHub Desktop.
Save Kristian-Roopnarine/e6851b063f4d4b6c550bca3a0d238d28 to your computer and use it in GitHub Desktop.
Code to reverse a singly linked list
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