chore(Python): added reverse linked list (#487)

pull/488/head
Akshit Arora 2021-09-26 20:18:39 +05:30 committed by GitHub
parent c25f746db6
commit 7ce554e085
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 52 additions and 0 deletions

View File

@ -11,6 +11,7 @@
1. [Doubly](linked_lists/doubly.py)
2. [Singly](linked_lists/singly.py)
3. [Reverse List](linked_lists/reverse-linkedlist.py)
## Multiplication

View File

@ -0,0 +1,51 @@
# reverse a given linkedlist
class Node:
# Constructor to initialize the node object
def __init__(self, data=0, next=None):
self.data = data
self.next = next
class LinkedList:
# Constructor to initialize head
def __init__(self) -> None:
self.head = None
# Function to insert a new node at the beginning
def push(self, data):
node = Node(data)
node.next = self.head
self.head = node
# Function to print the list from beginning
def printList(self):
temp = self.head
while temp:
print(temp.data, end=" ")
temp = temp.next
# Function to reverse the list
def reverse(self):
dummy = None
cur = self.head
while cur:
nextTemp = cur.next
cur.next = dummy
dummy = cur
cur = nextTemp
self.head = dummy
if __name__ == '__main__':
ll = LinkedList()
ll.push(1)
ll.push(2)
ll.push(3)
ll.push(4)
ll.push(5)
print("Before Reverse")
ll.printList()
ll.reverse() # reversing
print("\nAfter Reversing")
ll.printList()