Last active
September 21, 2015 19:28
-
-
Save martinvol/55f5e8dff93ffc5b0a6c to your computer and use it in GitHub Desktop.
How to reverse a linked-list using constant memory
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
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