Skip to content

Instantly share code, notes, and snippets.

@shaobos
Created March 5, 2023 05:26
Show Gist options
  • Save shaobos/ee2e4d05f5aff3eaa93f77ebc4860e85 to your computer and use it in GitHub Desktop.
Save shaobos/ee2e4d05f5aff3eaa93f77ebc4860e85 to your computer and use it in GitHub Desktop.
Reverse linked list - Python
class Node:
def __init__(self, val):
self.val = val
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def add(self, val):
node = Node(val)
if self.head is None:
self.head = node
else:
curr = self.head
while curr.next is not None:
curr = curr.next
curr.next = node
def reverse(self):
# TODO: implement
def print(self):
curr = self.head
while curr is not None:
print(curr.val, end=' ')
curr = curr.next
print()
list = LinkedList()
list.add(1)
list.add(2)
list.add(3)
list.add(4)
list.add(5)
print("Original list:")
list.print()
list.reverse()
print("Reversed list:")
list.print()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment