Program to reverse a Linked List

 In this program we will  see how we can reverse a linked list







input: 10=>20=>30=>40=>50=>
output: 50=>40=>30=>20=>10=>



class Node:
    def __init__(self,data):
        self.data = data
        self.next = None
class LinkedList:
    def __init__(self):
        self.head = None

    def display(self):
        temp = self.head
        while temp!=None:
            print(temp.data,end="=>")
            temp = temp.next

    def length(self):
        temp = self.head
        count = 0
        while temp!=None:
            count = count+1
            temp = temp.next
        return count
    def indexData(self,index):
        temp = self.head
        count =1
        while count!=index:
            temp = temp.next
            count = count+1
        return temp.data
    def reverse(self):
        count = self.length()
        while count>0:
            print(self.indexData(count),end="=>")
            count = count-1


if __name__=="__main__":
    llist = LinkedList()
    first = Node(10)
    second = Node(20)
    third = Node(30)
    fourth = Node(40)
    fifth = Node(50)
    llist.head = first
    first.next = second
    second.next = third
    third.next = fourth
    fourth.next = fifth
    llist.display()
    print("\nAfter reverese")
    llist.reverse()
    
    



No comments:

Post a Comment