Created
March 3, 2021 16:48
-
-
Save samgclarke/541991bf4d4d015dc9661ffd65e5d8eb to your computer and use it in GitHub Desktop.
Linked List and Reverse in Python
This file contains hidden or 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(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