Skip to content

Instantly share code, notes, and snippets.

@martinvol
Last active September 21, 2015 19:28
Show Gist options
  • Save martinvol/55f5e8dff93ffc5b0a6c to your computer and use it in GitHub Desktop.
Save martinvol/55f5e8dff93ffc5b0a6c to your computer and use it in GitHub Desktop.
How to reverse a linked-list using constant memory
def reverse(self):
if self.first == None or self.first.next == None:
# list is empty or has just one element,
# there's nothing to do
return
previous = None
current = self.first
next = current.next
while next:
# switching the pointers
current.next = previous
previous = current
current = next
next = next.next
current.next = previous
# change head of the list
self.first = current
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment