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
Selected Reading
Reverse 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: 1 ? 3 ? 5 ? 7, the reversed list will be: 7 ? 5 ? 3 ? 1
Algorithm
We can reverse a linked list using a recursive approach ?
- Define a recursive function
solve(head, back)wherebacktracks the 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 (
back) - Update
backto current node - If no more nodes exist, return current node as new head
- Recursively call the function with the next node
Implementation
Node Class and Helper Functions
class ListNode:
def __init__(self, data, next=None):
self.val = data
self.next = next
def make_list(elements):
if not elements:
return None
head = ListNode(elements[0])
ptr = head
for element in elements[1:]:
ptr.next = ListNode(element)
ptr = ptr.next
return head
def print_list(head):
values = []
ptr = head
while ptr:
values.append(str(ptr.val))
ptr = ptr.next
print(" ? ".join(values) if values else "Empty list")
Recursive Solution
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)
# Test the solution
original_list = make_list([1, 3, 5, 7])
print("Original list:")
print_list(original_list)
solution = Solution()
reversed_list = solution.reverseList(original_list)
print("\nReversed list:")
print_list(reversed_list)
Original list: 1 ? 3 ? 5 ? 7 Reversed list: 7 ? 5 ? 3 ? 1
Iterative Approach
We can also solve this problem iteratively using three pointers ?
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 solution
original_list = make_list([1, 3, 5, 7])
print("Original list:")
print_list(original_list)
solution = Solution()
reversed_list = solution.reverseListIterative(original_list)
print("\nReversed list (iterative):")
print_list(reversed_list)
Original list: 1 ? 3 ? 5 ? 7 Reversed list (iterative): 7 ? 5 ? 3 ? 1
Comparison
| Approach | Time Complexity | Space Complexity | Best For |
|---|---|---|---|
| Recursive | O(n) | O(n) | Educational purposes |
| Iterative | O(n) | O(1) | Production code |
Conclusion
Both recursive and iterative approaches can reverse a linked list in O(n) time. The iterative approach is preferred for its O(1) space complexity, while the recursive approach is more intuitive to understand.
Advertisements
