05
SepReverse Linked List
Reverse Linked List
The Reverse Linked List Problem involves reversing a singly linked list, where each node contains a value and a pointer to the next node. The task is to reverse the order of the nodes by updating the next pointers, such that the head becomes the tail and vice versa. This can be done iteratively or recursively, with the iterative approach being more space-efficient. The time complexity is O(n), where n is the number of nodes, and the space complexity is O(1) for the iterative approach.
Example:
- Input: Linked List = 1 -> 2 -> 3 -> 4 -> 5
- Output: 5 -> 4 -> 3 -> 2 -> 1
- Explanation: The linked list is reversed, with the head now pointing to node 5.
Logic
Enter a list of numbers (comma-separated) to create a linked list and reverse it using the iterative Reverse Linked List algorithm.
Program (Python - Iterative Reverse Linked List)
The following Python code implements an iterative solution to reverse a singly linked list with O(n) time complexity and O(1) space complexity.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def reverseList(head):
prev = None
current = head
while current:
# Store next node
next_node = current.next
# Reverse the link
current.next = prev
# Move prev and current one step forward
prev = current
current = next_node
return prev
# Helper function to create linked list from array
def createLinkedList(arr):
if not arr:
return None
head = ListNode(arr[0])
current = head
for val in arr[1:]:
current.next = ListNode(val)
current = current.next
return head
# Helper function to convert linked list to array for printing
def linkedListToArray(head):
result = []
current = head
while current:
result.append(current.val)
current = current.next
return result
# Example usage
arr = [1, 2, 3, 4, 5]
head = createLinkedList(arr)
reversed_head = reverseList(head)
print(linkedListToArray(reversed_head)) # Output: [5, 4, 3, 2, 1]
Output
For the input linked list created from [1, 2, 3, 4, 5], the output is:
[5, 4, 3, 2, 1]
Explanation
The linked list is reversed, with the head now pointing to node 5.
Take our Datastructures skill challenge to evaluate yourself!

In less than 5 minutes, with our skill challenge, you can identify your knowledge gaps and strengths in a given skill.