Wednesday, 21 November 2018

Python Program to Reverse a Singly Linked List

Python program to reverse a singly linked list is given below along with the output.

PROGRAM:

class Node:
        #defining a Node constructor
        def __init__(self,data):
            self.data = data
            self.next = None

    
class LinkedList:
        #defining a LinkedList constructor
        def __init__(self):
            self.head = None
    
        def insert_node(self,data):
            #checking of head node is still None
            if self.head == None:
                newnode = Node(data)
                self.head = newnode
            else:
                #we will traverse till the last node to append the new node
                current = self.head
                while current.next != None:
                    current = current.next
                
                current.next = Node(data)


        def print_linkedlist(self):
            current = self.head
            while current != None:
                print(current.data," -> ",end="")
                current = current.next
            print()


        def reverse(self):
            prevnode = None
            current = self.head
            nextnode = None
            #here we are reversing the Linked List
            while current != None:
                nextnode = current.next
                current.next = prevnode
                prevnode = current
                current = nextnode
            
            self.head = prevnode

linkedList = LinkedList()
linkedList.insert_node(10)
linkedList.insert_node(15)
linkedList.insert_node(20)
linkedList.insert_node(25)
linkedList.insert_node(30)

#let's first print the created linked list
print("\nThe created Linked List is: \n\n")
linkedList.print_linkedlist()

#Now reverse the linkedList
linkedList.reverse()


#Now print the reverse Linked List
print("\n\nTher reversed linked list is: \n\n")
linkedList.print_linkedlist()


OUTPUT:

 


EmoticonEmoticon