Open In App

Reverse a Linked List - Python

Last Updated : 21 Feb, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Given pointer to the head node of a linked list, the task is to reverse the linked list. We need to reverse the list by changing links between nodes.

Examples: 

Input: head: 1 -> 2 -> 3 -> 4 -> NULL
Output: head: 4 -> 3 -> 2 -> 1 -> NULL
Explanation: Reversed Linked List:

Reverse-a-Linked-List-2
Reversed Linked List



Input: head: 1 -> 2 -> 3 -> 4 -> 5 -> NULL
Output: head: 5 -> 4 -> 3 -> 2 -> 1 -> NULL
Explanation: Reversed Linked List:

Reverse-a-Linked-List-4
Reversed Linked List

Input : NULL
Output : NULL

Input : 1->NULL
Output : 1->NULL

1. Iterative Method  

The idea is to reverse the links of all nodes using three pointers:

  • prev: pointer to keep track of the previous node
  • curr: pointer to keep track of the current node
  • next: pointer to keep track of the next node

Starting from the first node, initialize curr with the head of linked list and next with the next node of curr. Update the next pointer of curr with prev. Finally, move the three pointer by updating prev with curr and curr with next.


Output
Given Linked List
85 15 4 20 
Reversed Linked List
20 4 15 85 
  • Time Complexity: O(N)
  • Auxiliary Space: O(1)

2. A Simpler and Tail Recursive Method 

The idea is to reach the last node of the linked list using recursion then start reversing the linked list from the last node.


Output
Given linked list
1 2 3 4 5 6 7 8 
Reverse linked list
8 7 6 5 4 3 2 1 
  • Time Complexity: O(N)
  • Auxiliary Space: O(1)

Please refer Reverse a linked list for more details!


Next Article

Similar Reads