How to Reverse a Linked List in Python
In this tutorial, we will learn how to reverse a Linked List in Python.
LinkedList is a sequence of data elements that are linked/connected through links. Each data element is connected to another data element. There is no standard library in Python Programming Language, It is Implemented by the concept of nodes in Data Structure. So, it is Data Structures in Python.
Creation of LinkedList:
As we said that a Linked list is created by using node class which is in Data Structures. Here we need to define some functions to create a Node.
class Node: def __init__(start, info): start.info = info start.next = None class LinkedList: def __init__(self): self.head = None
Reverse LinkedList in Python
Here we are shown that how to reverse the linked list. A linked list is reversed in only forward direction from the starting data element. We assigned the pointer of the next Node to the starting/current Node 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 self.head = prev
Inserting new node at the beginning:
Here we showed that inserting the new node at the beginning of the Linked list. To transfer the data element a new node is inserted. The transferred data element is stored in the new node as new data.
def push(self, new_data): new_node = Node(new_data) new_node.next = self.head self.head = new_node
Print the linked LinkedList:
Here we showed that how to print the linked LinkedList. After reversing the linked list, to print that we need to assign the head/starting element as temporary.
def printList(self): temp = self.head while(temp): print(temp.info) temp = temp.next
Inserting the values to the LinkedList:
llist = LinkedList() llist.push(20) llist.push(4) llist.push(21) llist.push(5) llist.push(22)
Print the Input and Output:
print ("Input Linked List") llist.printList() llist.reverse() print ("\n Reversed Linked List") llist.printList()
Input Linked List 22 5 21 4 20 Reversed Linked List 20 4 21 5 22
Also read: Random Singly Linked List Generator using Python
I was really confused about the inverse of linked lists in python by this tutorial i got clarified my all doubts, thank you!