Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Program to reverse a linked list in Python
A linked list is a linear data structure where elements are stored in nodes, and each node contains data and a pointer to the next node. Reversing a linked list means changing the direction of pointers so that the last node becomes the first node.
For example, if we have a linked list: 2 → 4 → 6 → 8, the reversed list will be: 8 → 6 → 4 → 2.
Approach
We can reverse a linked list using a recursive approach with these steps −
- Define a recursive function
solve(head, back)whereheadis current node andbackis previous node - If head is None, return head (base case)
- Store the next node in a temporary variable
- Point current node to the previous node
- Update the previous node to current node
- If next node is None, return current node (new head)
- Move to the next node and recursively call the function
Implementation
class ListNode:
def __init__(self, data, next=None):
self.val = data
self.next = next
def make_list(elements):
head = ListNode(elements[0])
for element in elements[1:]:
ptr = head
while ptr.next:
ptr = ptr.next
ptr.next = ListNode(element)
return head
def print_list(head):
ptr = head
result = []
while ptr:
result.append(str(ptr.val))
ptr = ptr.next
print(" → ".join(result))
class Solution:
def reverseList(self, head):
return self.solve(head, None)
def solve(self, head, back):
if not head:
return head
temp = head.next
head.next = back
back = head
if not temp:
return head
head = temp
return self.solve(head, back)
# Create and reverse a linked list
original_list = make_list([2, 4, 6, 8])
print("Original list:")
print_list(original_list)
# Recreate list since we modified it
original_list = make_list([2, 4, 6, 8])
solution = Solution()
reversed_list = solution.reverseList(original_list)
print("Reversed list:")
print_list(reversed_list)
Original list: 2 ? 4 ? 6 ? 8 Reversed list: 8 ? 6 ? 4 ? 2
How It Works
The recursive function works by:
- Storing the next node − Before changing pointers, save reference to next node
- Reversing the link − Point current node back to previous node
- Moving forward − Update pointers and recursively process remaining nodes
- Base cases − Handle empty list and end of list conditions
Iterative Approach
You can also reverse a linked list iteratively for better space complexity ?
class Solution:
def reverseListIterative(self, head):
prev = None
current = head
while current:
next_temp = current.next
current.next = prev
prev = current
current = next_temp
return prev
# Test iterative approach
original_list = make_list([1, 3, 5, 7])
print("Original list:")
print_list(original_list)
# Recreate list
original_list = make_list([1, 3, 5, 7])
solution = Solution()
reversed_list = solution.reverseListIterative(original_list)
print("Reversed list (iterative):")
print_list(reversed_list)
Original list: 1 ? 3 ? 5 ? 7 Reversed list (iterative): 7 ? 5 ? 3 ? 1
Conclusion
Reversing a linked list can be done recursively or iteratively. The recursive approach is intuitive but uses O(n) space due to function calls. The iterative approach is more space-efficient with O(1) space complexity.
