How to print the reverse of a linked list using recursion
Given a linked list, finding its reverse brings about a host of applications. For example, if we have a linked list sorted in ascending order, its reverse would be the linked list in descending order.
In this Answer, we'll learn to print the linked list in reverse without changing the linked list itself. This is best achieved through recursion.
Algorithm
The recursive approach to print the reverse of a linked list involves:
Recursive case: We traverse the linked list through a series of recursive calls to the next elements.
Base case: Once we reach the
, the recursive calls return the data assigned to that element.tail The end of the linked list
With this approach, the data of an element is printed, then we move to its previous element, all the way to the start of the list due to the recursive calls returning.
An example of this approach is illustrated in the following figure:
Implementation
The following is a Python implementation of the previously mentioned algorithm:
Note: The linked list is defined in the lines 13–16.
import linkedListdef printReverse(listNode):if listNode:printReverse(listNode.next)print(listNode.data, end = ' ')else:return# Driver Codeoriginal_list = linkedList.linkedList()original_list.insert(4)original_list.insert(7)original_list.insert(9)original_list.insert(5)print("Original Linked List:", end = ' ')original_list.printList()print()print("Reversed Linked List:", end = ' ')printReverse(original_list.head)
Code explanation
The file
linkedList.pycontains the classes for the linked list and its nodes, along with a few helper functions to print the list and insert nodes in it.The file
printReverse.pycontains the following:Lines 3–8: The function
printReverse(listNode)takes the head of the linked list aslistNodeand prints the reverse of the list.Lines 4–6: This is the recursive case. If we're currently at a node in the list and haven't reached its end, we continue to traverse the list by recursively calling
printReverse()on the next node.Lines 7–8: This is the base case. If we're at the end of the list, the recursive calls are returned, and the code in line 6 is then executed. This prints out the nodes in reverse as the recursive call stack is returned.
Line 11: This is the declaration of the linked list.
Lines 13–16: This is the definition of the linked list.
Lines 18–23: These print out the original linked list and call
printReverse().
Free Resources