-
-
Save wellsie/e7a5be87bce771a13904b4dc0f770f06 to your computer and use it in GitHub Desktop.
Reverse Singly Linked List Python
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 Node: | |
def __init__(self, value, next): | |
self.value = value | |
self.next = next | |
def dump(self): | |
print self.value | |
if self.next is not None: | |
self.next.dump() | |
def reverse(node): | |
# X | 3 -> 2 -> 1 -> 0 -> X | |
# 3 -> X | 2 -> 1 -> 0 -> X | |
# 2 -> 3 -> X | 1 -> 0 -> X | |
# 1 -> 2 -> 3 -> X | 0 -> X | |
# 0 -> 1 -> 2 -> 3 -> X | X | |
new_head = None | |
while node is not None: | |
next = node.next | |
node.next = new_head | |
new_head = node | |
node = next | |
return new_head | |
n0 = Node(0, None) | |
n1 = Node(1, n0) | |
n2 = Node(2, n1) | |
n3 = Node(3, n2) | |
n3.dump() | |
# 3 -> 2 -> 1 -> 0 | |
reverse(n3).dump() | |
# 0 -> 1 -> 2 -> 3 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment