Skip to content

Instantly share code, notes, and snippets.

@samgclarke
Created March 3, 2021 16:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save samgclarke/541991bf4d4d015dc9661ffd65e5d8eb to your computer and use it in GitHub Desktop.
Save samgclarke/541991bf4d4d015dc9661ffd65e5d8eb to your computer and use it in GitHub Desktop.
Linked List and Reverse in Python
class Node(object):
# constructor
def __init__(self, data=None, next=None):
self.data = data
self.next = next
class LinkedList(object):
def __init__(self):
self.head = None
def insert(self, data):
newnode = Node(data=data)
if self.head:
current = self.head
while current.next:
current = current.next
current.next = newnode
else:
self.head = newnode
def printLL(self):
current = self.head
while current:
print(current.data)
current = current.next
def reverse_list(list):
# initialize vars
previous = None
current = list.head
following = current.next
# go till the last element of the list
while current:
current.next = previous
previous = current
current = following
if following:
following = following.next
list.head = previous
if __name__ == '__main__':
LL = LinkedList()
LL.insert(3)
LL.insert(4)
LL.insert(5)
print("Linked List:")
LL.printLL()
print("Reverse Linked List:")
reverse_list(LL)
LL.printLL()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment