Reverse Linked List
In this lesson, we will learn how to reverse a linked list using recursion.
We'll cover the following
What is a Linked List?
A linked list is a data structure that stores data in the form of a sequence of nodes. Each Node holds data along with a forward pointer to the next Node in the list.
As you can see in the illustration below, a linked list is formed by Nodes which are linked together like a chain.
If you want to learn more about linked list have a look at our Interview Refresher course on Data Structures in Python.
What does “Reversing a Linked List” Mean?
A linked list contains a sequence of data. Our task is to reverse that sequence:
Implementation
import node as nclass LinkedList:def __init__(self) :self.head = Nonedef append(self, new_data):new_node = n.Node(new_data)if self.head is None : # If head node is nullself.head = new_nodereturnlast = self.headwhile (last.next):last = last.nextlast.next = new_node # add new node to end of listdef printList(self):temp = self.headwhile(temp):print(temp.data)temp = temp.next
Explanation
In the code snippet above, we pass our linked list myLinkedList
to the function reverse()
. This function checks whether the head of the linked list is null or not. If it exists, we call the helperFunction()
. This function is recursive and is actually where reversal of the linked list takes place.
In helperFunction()
, the nodes are reversed using the following statements:
next = current.next # The original next node of the current node is saved
current.next = previous # The next of the current node is updated
After this change, we recursively call the function again:
# Recursive case
helperFunction(myLinkedList, next, current)
# The current node in the next recursive call will be the "next" node that we saved.
# The previous node will be the parent function's current node
The base case for this problem will be when we reach the end of the linked list, in which case the next
node of the current
node will be None
. We will make this last node the head of the linked list, update its position and return
.
To better understand this algorithm have a look at the sequence of function calls:
In the next lesson, we will learn how to perform depth first traversal using recursion in graphs.