In place reversal of a Linked List Flashcards

(5 cards)

1
Q

What is the In-place Reversal pattern and when is it used?

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

What are the key steps for In-place Reversal?

A
  1. Initialize prev=None, curr=head.
  2. Save next node, reverse curr’s pointer to prev.
  3. Move prev and curr forward.
    Repeat until curr is None.

Action: Explain steps for [Reverse Linked List] aloud.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

How does In-place Reversal apply to [Reverse Linked List]?

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

What are the complexity and gotchas of In-place Reversal?

A

Complexity: Time: O(n), Space: O(1).
Gotchas: Empty list, single node, breaking links.

Action: List edge cases for [Reverse Linked List] aloud.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Code example for In-place Reversal.

A

```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
~~~

How well did you know this?
1
Not at all
2
3
4
5
Perfectly