In place reversal of a Linked List Flashcards
(5 cards)
What is the In-place Reversal pattern and when is it used?
Reverses a linked list by updating pointers in-place.
Use Case: Reverse list or sublist, reorder nodes.
Example: [Reverse Linked List]. Action: Verbalize use case aloud.
What are the key steps for In-place Reversal?
- Initialize prev=None, curr=head.
- Save next node, reverse curr’s pointer to prev.
- Move prev and curr forward.
Repeat until curr is None.
Action: Explain steps for [Reverse Linked List] aloud.
How does In-place Reversal apply to [Reverse Linked List]?
Problem: Reverse a singly linked list.
Approach: Update each node’s next to point to previous node.
Example: [Reverse Linked List].
Action: Verbalize solution logic aloud.
What are the complexity and gotchas of In-place Reversal?
Complexity: Time: O(n), Space: O(1).
Gotchas: Empty list, single node, breaking links.
Action: List edge cases for [Reverse Linked List] aloud.
Code example for In-place Reversal.
```python
from typing import Optional
class ListNode:
def __init__(self, val: int = 0, next: ‘ListNode’ = None) -> None:
self.val = val
self.next = next
def reverse_list(head: Optional[ListNode]) -> Optional[List[int]]:
prev: Optional[ListNode] = None
current: Optional[ListNode] = head
while current:
next_node = current.next
current.next = prev
prev = current
current = next_node
return prev
~~~