reversing linked lists

Discussion in 'Python' started by Kevin Papenhaus, Aug 11, 2022.

  1. Kevin Papenhaus

    Kevin Papenhaus New Member

    Joined:
    Mar 7, 2022
    Messages:
    1
    Likes Received:
    0
    Trophy Points:
    1
    Gender:
    Male
    Could someone please explain for this example, how this linked list is reversed and what would be the benefit of doing this? This is a online example of a linked list reversed. My question is why do this and could you also confirm if its right? Could you further elaborate on this subject of a linked list reversed.





    file handling events

    to reverse a linked list

    Code:
    # Python program to reverse a linked list
    # Time Complexity : O(n)
    # Space Complexity : O(n) as 'next'
    #variable is getting created in each loop.
     
    # Node class
     
     
    class Node:
     
    # Constructor to initialize the node object
        def __init__(self, data):
            self.data = data
            self.next = None
     
     
    class LinkedList:
     
        # Function to initialize head
        def __init__(self):
            self.head = None
     
        # Function to reverse the linked list
        def reverse(self):
            prev = None
            current = self.head
            while(current is not None):
                next = current.next
    
    
     current.next = prev
                prev = current
                current = next
            self.head = prev
     
        # Function to insert a new node at the beginning
        def push(self, new_data):
            new_node = Node(new_data)
            new_node.next = self.head
            self.head = new_node
     
        # Utility function to print the LinkedList
        def printList(self):
    
    
     temp = self.head
            while(temp):
                print (temp.data,end=" ")
                temp = temp.next
     
     
    # Driver program to test above functions
    llist = LinkedList()
    llist.push(20)
    llist.push(4)
    llist.push(15)
    llist.push(85)
     
    print ("Given Linked List")
    llist.printList()
    llist.reverse()
    print ("\nReversed Linked List")
    llist.printList()
     

Share This Page

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice