Python 3 Script to Reverse the Elements of Linear Linked List Full Project For Beginners

 

 

main.py

 

 

class Node:
    def __init__(self, data=None, link=None):
        self.data=data
        self.link=link
    def __str__(self):
        return str(self.data)

class LinearList:
    def __init__(self, start=None):
        self.start=start
        
    def printList(self):
        ptr=self.start
        while ptr:
            print(ptr)
            ptr=ptr.link
        print()
    
    def revList(self):
        curr=self.start
        prev=None
        nxt=None
                
        while curr:
                nxt=curr.link
                curr.link=prev
                prev=curr
                curr=nxt
                
        self.start= prev
  
           
        
node1=Node('amy')
node2=Node('Bob')
node3=Node('Cathy')
node4=Node('Dan')
node5=Node('Eva')
node6=Node('Fred')
node7=Node('Zoe')
node1.link=node2
node2.link=node3
node3.link=node4
node4.link=node5
node5.link=node6
node6.link=node7
ll=LinearList(node1)
print("Linked List Initially")
ll.printList()
ll.revList()
print("Linked List after Reversal")
ll.printList()

Leave a Reply