Last active
July 14, 2024 20:14
-
-
Save primaryobjects/b49c3b5a635583c8c7a43fde3177cf99 to your computer and use it in GitHub Desktop.
Reverse a linked list in Python https://replit.com/@primaryobjects/ReverseLinkedList
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
from __future__ import annotations | |
class Node: | |
value = None | |
next = None | |
def __init__(self, value: int, next: Node = None): | |
self.value = value | |
self.next = next | |
def print(self): | |
print(f'{self.value}') | |
def to_list(self): | |
result = [] | |
head = self | |
while head: | |
result.append(head.value) | |
head = head.next | |
return result | |
def reverse_linked_list(node: Node): | |
current = node | |
prev = None | |
# While we have a valid node, continue reversing. | |
while current: | |
# Set a temp pointer to the child node. | |
child = current.next | |
# Reverse the current node by pointing its next to the previous node. | |
current.next = prev | |
# Set the previous pointer to the current node. | |
prev = current | |
# Move to the next node. | |
current = child | |
return prev | |
list1 = Node(1, Node(2, Node(3, Node(4, Node(5))))) | |
print(list1.to_list()) | |
list2 = reverse_linked_list(list1) | |
print(list2.to_list()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment