How To Reverse A Linked List In Python
How To Reverse A Linked List In Python
Let’s understand the problem statement first to reverse a linked list in Python. The challenge is to
reverse a linked list in situ given its head pointer. This indicates that neither shuffling the data field
nor using auxiliary space to build a new linked list is permitted. In Python, this issue is frequently
referred to as linked list reverse.
Example
Suppose the nodes of the linked list are numbered and links are represented using arrows. So if we
are given the head pointer to the linked list: 1 → 2 → 3 → 4 → 5 Then our algorithm should provide a
linked list reverse in Python as 5 → 4 → 3 → 2 → 1 The new head pointer should be at node 5.
Algorithm
The basic idea of the problem is to traverse the linked list and reverse the links between nodes one
at a time. For example, suppose we start with: 1 → 2 → 3 → 4 → 5 First, we will reverse the link
between node 1 and node 2. 1 ← 2 Next, we will reverse the link between node 2 and node 3. 1 ← 2
← 3 We will repeat the process until we reverse all the links to get: 1 ← 2 ← 3 ← 4 ← 5
We will discuss two different approaches for writing a python program to reverse a linked list below.
prev will initially point to None and the curr will point to the head of the list.
Now, we have to traverse through the list till the curr becomes None.
For every node, we are going to store the next of curr in next and then will make the next of
current point to prev. Finally we will make prev equal to curr, and curr equal to next.
By performing the above operations, we are changing the links of every node and ultimately
reversing the list.
After pointing to prev, we will make the prev equal to the curr, and curr equal to the next.
In the end, after the full traversal, the prev will be our head (head = prev).
Dry Run for the Iterative Approach to Reverse a Linked List in Python