Ask a Question
Select Model
Answer
Here is a clear and standard Python function to reverse a singly linked list.
This example assumes a basic singly linked list node defined as:
```python
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
```
The function to reverse the linked list iteratively:
```python
def reverse_linked_list(head):
prev = None
current = head
while current:
next_node = current.next # temporarily store the next node
current.next = prev # reverse the current node's pointer
prev = current # move prev and current one step forward
current = next_node
return prev # prev will be the new head at the end
```
If you want a recursive approach, here is one:
```python
def reverse_linked_list_recursive(head):
if head is None or head.next is None:
return head
new_head = reverse_linked_list_recursive(head.next)
head.next.next = head
head.next = None
return new_head
```
These implementations are the standard ways to reverse a singly linked list in Python.
Model
GPT-4.1 Mini
Input Tokens
14047
Output Tokens
246
Total Tokens
14293
Est. Cost
$0.012025